<?php

/*
CDR表处理程序
2016-8-17
zhangtuo   for  好未来
 */
function cdrProcess($calls,$self) {
	if(empty($calls)){
		return null;
	}

	$user_list = M('m_user')->Field('user_id,user_exten,d_id')->select();
	$arr_user = array();
	foreach($user_list as $v){
		$arr_user[$v['user_exten']] = array('user_id' =>$v['user_id'],'d_id'=>$v['d_id']);
	}
	//dump($arr_user);
	$arr_call_status = getFieldOptArray(17,"call_status", "ext2");
	$arr_call_type = getFieldOptArray(17,"call_type", "ext2");
	$m_exten_calls = M('exten_calls');
	$m_queue_calls = M('queue_calls');
	$m_contacts = M('Contacts');
	$m_numlibrary = M('Numlibrary');

	foreach($calls as $call) {
		if($call['call_type'] == "internal"){
			$call['call_type'] = "out";
		}elseif($call['call_type'] == "external"){
			$call['call_type'] = "in";
		}

		if($call['disposition'] == "FAILED"){
			$call['disposition'] = "NO ANSWER";
		}

		//监听产生两条记录，过滤掉
		if(strstr($call['dst'],"*998001") || strstr($call['clid'],"*998001") || strstr($call['clid'],"cc") ) continue; 


		switch(strtolower($call['call_type'])){
			case 'out':
				if(strtolower($call['lastapp']) !="dial" && $call['lastapp'] !='Congestion' && $call['lastapp'] !='' && $call['lastapp'] != 'Busy') continue; //对于点击外呼，没有接通的，它会产生两条通话记录，不等于dial的要跳过 ？？

				//dump();
				$info['id'] = $call['id'];
				$info['call_time'] = strtotime($call['calldate']);
				$info['call_status'] = $arr_call_status[$call['disposition']]['id'];	
				$info['call_type'] = $arr_call_type['out']['id'];		
				$info['src'] = $call['cnum'];
				$info['dst'] = $call['dst'];
				$info['recordingfile'] = $call['recordingfile'];
				$info['cid'] = $call['outbound_cnum']; //透传号码

				//点击外呼，通话时长处理，如果没接通的，billsec也有值
				if(strstr($call['cnam'],'cc')){
					if($call['disposition'] !='ANSWERED'){
						$info['wait_time'] =  $call['duration'];
						$info['billsec'] = 0;
					}else{
						$info['billsec']  = $m_exten_calls->where("Channel='%s' AND Uniqueid='%s'",$call['channel'],$call['uniqueid'])->getField('billsec');
						dump($m_exten_calls->getlastsql());
						dump($info['billsec']);
						$info['wait_time'] = $call['duration'] - $info['billsec'] ;
					}
				}else{
					if($call['disposition'] !='ANSWERED'){
						$info['wait_time'] =  $call['duration'];
						$info['billsec'] = 0;
					}else{
						$info['wait_time'] =  $call['duration'] -  $call['billsec'];
						$info['billsec'] = $call['billsec'];
					}
				}
				$user_id = $arr_user[$call['cnum']] ? $arr_user[$call['cnum']]['user_id'] : 0 ;
				$d_id = $arr_user[$call['cnum']] ? $arr_user[$call['cnum']]['d_id'] : 0 ;
				$info['user_id'] = ( $call['user_id'] == "0" ) ? $user_id : $call['user_id'];
				$info['d_id'] = ( $info['user_id'] == "0" ) ? 0 : $d_id ;
				$info['customer_id'] = $call['customer_id'];	
			break;
			case 'q'://队列来电或者服务评分,看dcontext
			case 'feedback':
			//dump($call);
                                unset($info);
			//	$arr_q_info = $m_queue_calls->where("Channel='%s' AND CallerIDNum='%s' AND Uniqueid='%s'",$call['channel'],$call['cnum'],$call['uniqueid'])->field('is_fangqi,HoldTime')->find();
				//if(empty($arr_q_info)) continue;// 表示通话还没结束，继续等等
                           if (empty($call['dstchannel'])) {
                              $arr_q_info = $m_queue_calls->where("Channel='%s' AND CallerIDNum='%s' AND Uniqueid='%s' AND time_begin='%s'",$call['channel'],$call['cnum'],$call['uniqueid'],strtotime($call['calldate']))->field('is_fangqi,HoldTime')->find();
                              if(empty($arr_q_info)){
                                    $arr_q_info = $m_queue_calls->where("Channel='%s' AND CallerIDNum='%s' AND Uniqueid='%s' ",$call['channel'],$call['cnum'],$call['uniqueid'])->field('is_fangqi,HoldTime')->find();
                                
                                    }
                             }else{
                                $arr_q_info = $m_queue_calls->where("Channel='%s' AND CallerIDNum='%s' AND Uniqueid='%s' ",$call['channel'],$call['cnum'],$call['uniqueid'])->field('is_fangqi,HoldTime')->find();
                             }
                 if(empty($arr_q_info) && empty($call['recordingfile']) && empty($call['billsec'])) {continue;} else{
                 	if ($call['recordingfile'] == 'BUSY') {
                 	 $arr_q_info['is_fangqi'] =$arr_q_info['is_fangqi']?$arr_q_info['is_fangqi']:1; 	
                 	}else{
                 	  $arr_q_info['is_fangqi'] =$arr_q_info['is_fangqi']?$arr_q_info['is_fangqi']:0; 	
                 	} 
                 	
                 }
                // dump($call['src']);
				$info['id'] = $call['id'];
				$info['call_time'] = strtotime($call['calldate']);
				$info['queue_id'] = $call['dst'];
				$info['src'] = $call['src'];
				$info['did'] = $call['did'];
				$info['call_type'] = $arr_call_type['in']['id'];
				$info['recordingfile'] = $call['recordingfile'];
				$info['customer_id'] = $call['customer_id'];
				//如果是放弃的
				//out($info);
				if($arr_q_info['is_fangqi'] == 1){
					$info['wait_time'] =  $arr_q_info['HoldTime']?$arr_q_info['HoldTime']:0;
					$info['billsec'] = 0;
					//表示已经分给坐席的，坐席漏接
					if(strstr($call['dstchannel'],'from-queue')){
						$info['call_status'] = $arr_call_status['NO ANSWER']['id'];
						//Local/8001@from-queue-00000032;1
						$tmp = explode('@',$call['dstchannel']);
						$tmp = explode('/',$tmp[0]);
						$tmp =$tmp[1];
						$user_id = $arr_user[$tmp] ? $arr_user[$tmp] : 0 ;
						$info['user_id'] = $user_id ? $user_id : 0;

						$user_id = $arr_user[$tmp]['user_id'] ? $arr_user[$tmp]['user_id'] : 0;
						$d_id = $arr_user[$tmp]['d_id'] ? $arr_user[$tmp]['d_id'] : 0 ;
						$info['user_id'] =  $user_id ? $user_id : 0;
						$info['d_id'] = ( $info['user_id'] == "0" ) ? 0 : $d_id ;
						$info['dst'] = $tmp;
					//表示没有空闲的坐席可分配,状态是排队放弃
					}else{
						$info['call_status'] = $arr_call_status['qfangqi']['id'];
						$info['user_id'] = 0;
						$info['dst'] = $call['dst'];
					}

				//客户如果没有放弃，说明是已经分给坐席，并且接通了的
				}else{
					//去exten_calls表中找一下通话时长
					$arr_e_info = $m_exten_calls->where("Channel='%s' AND CallerIDNum='%s' AND Uniqueid='%s'",$call['channel'],$call['cnum'],$call['uniqueid'])->field('billsec')->find();
					//dump( $m_exten_calls->getLastSql());
					//dump($arr_e_info);
					if(empty($arr_e_info) && empty($call['billsec'])) continue;// 表示通话还没结束，继续等等

					$info['wait_time'] =  $arr_q_info['HoldTime']?$arr_q_info['HoldTime']:3;
					$info['billsec'] = $arr_e_info['billsec']?$arr_e_info['billsec']:$call['billsec'];
					$info['call_status'] = $arr_call_status['ANSWERED']['id'];
					//Local/8001@from-queue-00000032;1
					if($call['call_type'] == 'feedback')
					{
					 $exten   = $call['dst_cnam'];
					}else{
					 $tmp = explode('@',$call['dstchannel']);
					 $tmp = explode('/',$tmp[0]);
					 $exten = $tmp[1];
					}
					$info['user_id'] = $arr_user[$exten]['user_id']  ? $arr_user[$exten]['user_id']  : 0 ;
					$info['d_id']    = $arr_user[$exten]['d_id']     ? $arr_user[$exten]['d_id']     : 0 ;
					$info['dst']     = $exten;
				}
                              //dump($info);
			break;
			case 'in': 

				//过滤掉IVR类型的
				if($call['lastapp']  == "BackGround" || strstr($call['dcontext'],'ivr')){
					$info['id'] = $call['id'];
					$info['call_time'] = strtotime($call['calldate']);
					$info['call_status'] = $arr_call_status['ivr']['id'];
					$info['call_type'] = $arr_call_type['in']['id'];		
					$info['src'] = $call['src'];
					$info['dst'] = $call['dcontext'];
					$info['billsec'] = $call['billsec'];
                                        //$tmp = explode('@',$call['dstchannel']);
					//$tmp = explode('/',$tmp[0]);
					//$info['dst'] = $tmp[1];
					$info['wait_time'] = $call['duration'] - $call['billsec'];
					$info['recordingfile'] = $call['recordingfile'];
					$info['did'] = $call['did'];
                                       // $tmp_queue = explode('-',$call['lastdata']);
				//	$info['queue_id']        = $tmp_queue[1]?$tmp_queue[1]:0; 
                                        $info['queue_id']        =0;
					continue;		
				}

			    $arr_q_info = $m_queue_calls->where("Uniqueid='%s'",$call['uniqueid'])->field('is_fangqi,HoldTime')->find();
				if(strtolower($call['lastapp']) !="dial" AND strtolower($call['lastapp']) !="queue") continue; 
				$info['id'] = $call['id'];
				$info['call_time'] = strtotime($call['calldate']);
				if(is_array($arr_q_info) && $arr_q_info['is_fangqi'] == 1)
				{
				  $info['call_status']   = $arr_call_status['qfangqi']['id'];
				  $info['wait_time']     = $arr_q_info['HoldTime'];
				  $info['billsec']       = 0;
				}elseif(is_array($arr_q_info)){
				  $info['call_status']   = $arr_call_status[$call['disposition']]['id'];
				  $info['wait_time']     = $arr_q_info['HoldTime'];
				  $info['billsec']       = $call['duration'];
				}else{
				  $info['call_status']   = $arr_call_status[$call['disposition']]['id'];	
				  if($call['disposition'] !='ANSWERED'){
					  $info['wait_time'] =  $call['duration'];
					  $info['billsec']   = 0;
				  }else{
					  //如果是直接转给分机的，应该去查查的实际通话时长
					  $info['wait_time'] =  $call['duration'] -  $call['billsec'];
					  $info['billsec']   = $call['billsec'];
				  }
				}
				$info['call_type']       = $arr_call_type['in']['id'];		
				$info['src']             = $call['cnum'];
				//$info['dst']             = $call['dst'];
               if ($call['dst']=='*15'  || substr($call['dst'],0,2)==90 || substr($call['dst'],0,2)==80) {
               	   if (strstr($call['dstchannel'],"@")) {
               	   	$tmp = explode('@',$call['dstchannel']);
				    $tmp = explode('/',$tmp[0]);
				    $info['dst'] = $tmp[1];
               	   }else{
               	   	$info['dst']             = $call['dst'];
               	   }
				    
				}else{
				    $info['dst']             = $call['dst'];
				}
				$info['recordingfile']   = $call['recordingfile'];
				$info['did']             = $call['did']; 
				$user_id                 = $arr_user[$call['dst']] ? $arr_user[$call['dst']]['user_id'] : 0 ;
				$d_id                    = $arr_user[$call['dst']] ? $arr_user[$call['dst']]['d_id'] : 0 ;
				$info['user_id']         = ( $call['user_id'] == "0" ) ? $user_id : $call['user_id'];
				$info['d_id']            = ( $info['user_id'] == "0" ) ? 0 : $d_id ;
				$info['customer_id']     = $call['customer_id'];
				$info['queue_id']        = $call['queue_id'];
			break;
			//其它情况
		    default :
				if($call['lastapp']  == "BackGround" || strstr($call['dcontext'],'ivr')){
					$info['id'] = $call['id'];
					$info['call_time'] = strtotime($call['calldate']);
					$info['call_status'] = $arr_call_status['ivr']['id'];
					$info['call_type'] = $arr_call_type['in']['id'];		
					$info['src'] = $call['src'];
					$info['dst'] = $call['dcontext'];
					$info['billsec'] = $call['billsec'];
					$info['wait_time'] = $call['duration'] - $call['billsec'];
					$info['recordingfile'] = $call['recordingfile'];
					$info['did'] = $call['did']; 		
				}

			break;

		}
		
		// $info['did'] = $call['did'];
		// $info['call_status'] = $arr_call_status[$call['call_status']]['id'];	
		// $info['call_type'] = $arr_call_type[$call['call_type']]['id'];		
		$info['uniqueid']	= $call['uniqueid']; 
                $info['duration']       = $call['duration'];

		if($info['call_type'] == $arr_call_type['in']['id']){ //呼入查src、呼出查dst
			$arr_phone  = getPhoneArray($info['src']);
		}else{
			$arr_phone  = getPhoneArray($info['dst']);
		}
			
		if(!empty($call['call_corp']) && !empty($call['call_province']) && !empty($call['call_city'])){
			$info['call_province'] = base64_decode($call['call_province']);
			$info['call_city'] = base64_decode($call['call_city']);	
			//$info['call_corp'] = base64_decode($call['call_corp']);
			$info['call_corp']= base64_decode($call['call_corp']);	
		}else{
			//查找归属地
	        if($arr_phone['success']){
	            //截取号段
	            /*$mobile = substr($arr_phone['phone'], 0, 7);              
	            //查询号段所属的省份、城市、运营商、区号，并返回数绿    
	            $row = $m_numlibrary->where("Mobile = '".$mobile."'")->field('Province,City,Corp')->find();
				$info['call_province'] = $row['Province'];
				$info['call_city'] = $row['City'];	
				$info['call_corp']= $row['Corp'];*/
                               // file_put_contents('dddphone.txt', $arr_phone['phone']."\r\n",FILE_APPEND);
                                    if ($arr_phone['type']=='guhua') {
		                      	$row  = getNumlibrary('0'.$arr_phone['phone']);
		                    }else{
		                     	$row  = getNumlibrary($arr_phone['phone']);
		                    }
		                  
	                       // $row  = getNumlibrary($arr_phone['phone']);
	                        $citys = explode(' ',$row['Province']);
				$info['call_province'] = $citys[0]?$citys[0]:0;
				$info['call_city'] = $citys[1]?$citys[1]:0;	
				$info['call_corp']= $row['Corp']?$row['Corp']:0;
	        }			

		}
		switch ($info['call_corp']) {
			case '中国移动':
				$info['call_corp'] = 102;
				break;
			case '中国联通':
				$info['call_corp'] = 103;
				break;
			case '中国电信':
				$info['call_corp'] = 105;
				break;
			
			default:
				$info['call_corp'] = 104;
				break;
			}	

		//客户编号赋值
		if(empty($call['customer_id']) || $call['customer_id'] ==0 ){
			if($info['call_type'] == $arr_call_type['in']['id']){ //呼入查src、呼出查dst
				$arr_phone  = getPhoneArray($info['src']);
			}else{
				$arr_phone  = getPhoneArray($info['dst']);
			}

			if($arr_phone['success']){
				$customer_arr =$m_contacts->where('phone=%s',$arr_phone['phone'])->field('customer_id')->find();
				dump($customer_arr );
				if($customer_arr['customer_id']){
					$info['customer_id'] = $customer_arr['customer_id'];
				}

			}
		}
              if(!$info['user_id']){	
                $info['user_id'] = $arr_user[$info['dst']]?$arr_user[$info['dst']]['user_id']:'';
	        $info['d_id']     = $arr_user[$info['dst']]?$arr_user[$info['dst']]['d_id']:'';
                }
                $info['did']     =  $info['did']?$info['did']:87702800;
                //等待时长   接通时长  振铃时长 处理
            $du = $info['duration'];
           if ($info['call_type']==331) {
		           switch ($info['call_status']) {
		           	case 342: //ivr
		           	    $info['billsec']=0;
		           		$info['duration']=0;
		           		$info['wait_time']=$du;
		           		break;
		           	case 343://排队放弃
		           		$info['billsec']=0;
		           		$info['duration']=0;
		           		$info['wait_time']=$du;
		           		break;
		           	case 334://振铃未接
		           		$info['billsec']=0;
		           		if ($du>15) {
		           			$info['duration']=15;
		           		}else{
		           			$info['duration']=$du;
		           		}
		           		$info['wait_time']=0;
		           		break;
		                case 341://忙线
		                 	$info['call_status'] = 333;//接通
		                	break;
		                default:
		                        break;
		           	}
           	}
		$arr[] = $info;
		
	}
	return $arr;
}


function cdrProcess_old($calls,$self) {
	if(empty($calls)){
		return null;
	}

	$user_list = M('m_user')->Field('user_id,user_exten,d_id')->select();
	$arr_user = array();
	foreach($user_list as $v){
		$arr_user[$v['user_exten']] = array('user_id' =>$v['user_id'],'d_id'=>$v['d_id']);
	}
	//dump($arr_user);
	$arr_call_status = getFieldOptArray(17,"call_status", "ext2");
	$arr_call_type = getFieldOptArray(17,"call_type", "ext2");
	$m_exten_calls = M('exten_calls');
	$m_queue_calls = M('queue_calls');

	foreach($calls as &$call) {
		if($call['call_type'] == "internal"){
			$call['call_type'] = "out";
		}elseif($call['call_type'] == "external"){
			$call['call_type'] = "in";
		}

		if($call['disposition'] == "FAILED"){
			$call['disposition'] = "NO ANSWER";
		}

		//unset($info);
		switch($call['call_type']){
			case "out":
			//dump($info);
				if(strtolower($call['lastapp']) !="dial") continue; //对于点击外呼，没有接通的，它会产生两条通话记录，不等于dial的要跳过 ？？
				$info['id'] = $call['id'];
				$info['call_time'] = strtotime($call['calldate']);
				$info['call_status'] = $arr_call_status[$call['disposition']]['id'];	
				$info['call_type'] = $arr_call_type['out']['id'];		
				$info['src'] = $call['cnum'];
				$info['dst'] = $call['dst'];
				$info['recordingfile'] = $call['recordingfile'];
				$info['cid'] = $call['outbound_cnum']; //透传号码

				//点击外呼，通话时长处理，如果没接通的，billsec也有值
				if(strstr($call['cnam'],'cc')){
					if($call['disposition'] !='ANSWERED'){
						$info['wait_time'] =  $call['duration'];
						$info['billsec'] = 0;
					}else{
						$info['billsec']  = $m_exten_calls->where("Channel='%s' AND Uniqueid='%s'",$call['channel'],$call['uniqueid'])->getField('billsec');
						dump($m_exten_calls->getlastsql());
						dump($info['billsec']);
						$info['wait_time'] = $call['duration'] - $info['billsec'] ;
					}
				}else{
					if($call['disposition'] !='ANSWERED'){
						$info['wait_time'] =  $call['duration'];
						$info['billsec'] = 0;
					}else{
						$info['wait_time'] =  $call['duration'] -  $call['billsec'];
						$info['billsec'] = $call['billsec'];
					}
				}
				$user_id = $arr_user[$call['cnum']] ? $arr_user[$call['cnum']]['user_id'] : 0 ;
				$d_id = $arr_user[$call['cnum']] ? $arr_user[$call['cnum']]['d_id'] : 0 ;
				$info['user_id'] = ( $call['user_id'] == "0" ) ? $user_id : $call['user_id'];
				$info['d_id'] = ( $info['user_id'] == "0" ) ? 0 : $d_id ;
				$info['customer_id'] = $call['customer_id'];	
			break;
			case "q"://队列来电

				$arr_q_info = $m_queue_calls->where("Channel='%s' AND CallerIDNum='%s' AND Uniqueid='%s'",$call['channel'],$call['cnum'],$call['uniqueid'])->field('is_fangqi,HoldTime')->find();
				//dump( $m_queue_calls->getLastSql());
				//dump($arr_q_info);
				if(empty($arr_q_info)) continue;// 表示通话还没结束，继续等等

				$info['id'] = $call['id'];
				$info['call_time'] = strtotime($call['calldate']);
				$info['queue_id'] = $call['dst'];
				$info['src'] = $call['src'];
				$info['did'] = $call['did'];
				$info['call_type'] = $arr_call_type['in']['id'];
				$info['recordingfile'] = $call['recordingfile'];
				//如果是放弃的
				if($arr_q_info['is_fangqi'] == 1){
					$info['wait_time'] =  $arr_q_info['HoldTime'];
					$info['billsec'] = 0;
					//表示已经分给坐席的，坐席漏接
					if(strstr($call['dstchannel'],'from-queue')){
						$info['call_status'] = $arr_call_status['NO ANSWER']['id'];
						//Local/8001@from-queue-00000032;1
						$tmp = explode('@',$call['dstchannel']);
						$tmp = explode('/',$tmp[0]);
						$tmp =$tmp[1];
						$user_id = $arr_user[$tmp] ? $arr_user[$tmp] : 0 ;
						$info['user_id'] = $user_id ? $user_id : 0;

						$user_id = $arr_user[$tmp]['user_id'] ? $arr_user[$tmp]['user_id'] : 0;
						$d_id = $arr_user[$tmp]['d_id'] ? $arr_user[$tmp]['d_id'] : 0 ;
						$info['user_id'] =  $user_id ? $user_id : 0;
						$info['d_id'] = ( $info['user_id'] == "0" ) ? 0 : $d_id ;
						$info['dst'] = $tmp;
					//表示没有空闲的坐席可分配,状态是排队放弃
					}else{
						$info['call_status'] = $arr_call_status['qfangqi']['id'];
						$info['user_id'] = 0;
						$info['dst'] = $call['dst'];
					}

				//客户如果没有放弃，说明是已经分给坐席，并且接通了的
				}else{
					//去exten_calls表中找一下通话时长
					$arr_e_info = $m_exten_calls->where("Channel='%s' AND CallerIDNum='%s' AND Uniqueid='%s'",$call['channel'],$call['cnum'],$call['uniqueid'])->field('billsec')->find();
					//dump( $m_exten_calls->getLastSql());
					//dump($arr_e_info);
					if(empty($arr_e_info)) continue;// 表示通话还没结束，继续等等

					$info['wait_time'] =  $arr_q_info['HoldTime'];
					$info['billsec'] = $arr_e_info['billsec'];
					$info['call_status'] = $arr_call_status['ANSWERED']['id'];
					//Local/8001@from-queue-00000032;1
					$tmp = explode('@',$call['dstchannel']);
					$tmp = explode('/',$tmp[0]);
					$tmp =$tmp[1];
					$user_id = $arr_user[$tmp]['user_id']  ? $arr_user[$tmp]['user_id']  : 0 ;
					$d_id = $arr_user[$tmp]['d_id']  ? $arr_user[$tmp]['d_id']  : 0 ;
					$info['user_id'] = $user_id ? $user_id : 0;
					$info['d_id'] = $d_id ? $d_id : 0;
					$info['dst'] = $tmp;
				}
			break;
			case "in":
				if(strtolower($call['lastapp']) !="dial") continue; 
				$info['id'] = $call['id'];
				$info['call_time'] = strtotime($call['calldate']);
				$info['call_status'] = $arr_call_status[$call['disposition']]['id'];	
				$info['call_type'] = $arr_call_type['in']['id'];		
				$info['src'] = $call['cnum'];
				$info['dst'] = $call['dst'];
				$info['recordingfile'] = $call['recordingfile'];
				$info['did'] = $call['did']; 

				if($call['disposition'] !='ANSWERED'){
					$info['wait_time'] =  $call['duration'];
					$info['billsec'] = 0;
				}else{
					//如果是直接转给分机的，应该去查查的实际通话时长
					$info['wait_time'] =  $call['duration'] -  $call['billsec'];
					$info['billsec'] = $call['billsec'];
				}
				
				$user_id = $arr_user[$call['dst']] ? $arr_user[$call['dst']]['user_id'] : 0 ;
				$d_id = $arr_user[$call['dst']] ? $arr_user[$call['dst']]['d_id'] : 0 ;
				$info['user_id'] = ( $call['user_id'] == "0" ) ? $user_id : $call['user_id'];
				$info['d_id'] = ( $info['user_id'] == "0" ) ? 0 : $d_id ;
				$info['customer_id'] = $call['customer_id'];
			break;
			//其它情况
			 default :
			if($call['lastapp']  == "BackGround" || strstr($call['dcontext'],'ivr')){
				$info['id'] = $call['id'];
				$info['call_time'] = strtotime($call['calldate']);
				$info['call_status'] = $arr_call_status['ivr']['id'];
				$info['call_type'] = $arr_call_type['in']['id'];		
				$info['src'] = $call['src'];
				$info['dst'] = $call['dcontext'];
				$info['billsec'] = $call['billsec'];
				$info['wait_time'] = $call['duration'] - $call['billsec'];
				$info['recordingfile'] = $call['recordingfile'];
				$info['did'] = $call['did']; 		
			}

			break;

		}
		//dump($call['call_type']);
		
		// $info['did'] = $call['did'];
		// $info['call_status'] = $arr_call_status[$call['call_status']]['id'];	
		// $info['call_type'] = $arr_call_type[$call['call_type']]['id'];		
		$info['uniqueid']	= $call['uniqueid']; 
		$arr[] = $info;
		
	}
	return $arr;
}




function cdrProcess11($calls,$self) {
	$arr =array();
	$arr_call_status = getFieldOptArray(17,"call_status", "ext2");
	$arr_call_type = getFieldOptArray(17,"call_type", "ext2");
	//dump($arr_call_type);
	foreach($calls as &$call) {
		$app = strtolower($call['lastapp']);
		switch($app) {
			case 'dial':
				//$info['call_status'] = $arr_call_status[$call['disposition']]['id'];
				$call['call_status'] = $call['disposition'];
				if($call['call_type'] == "external"){
					$call['call_type'] = "in";
				}
				switch($call['disposition']) {
					case 'ANSWERED':
						$info['recordingfile'] = $call['recordingfile'];
						if(strlen($call['src']) == 4) {
							$info['dst'] = $call['dst'];
							$info['src'] = $call['src'];

						} elseif(strlen($call['dst']) == 4) {
							$info['dst'] = $call['dst'];
							$info['src'] = $call['src'];
						} elseif(strlen($call['cnum']) == 4) {
							$info['dst'] = $call['dst'];
							$info['src'] = $call['cnum'];
						} else {
							$info['dst'] = $call['dst'];
							$info['src'] = $call['src'];
						}
					break;
					case 'NO ANSWER':
						$info['call_status'] = 334;
						if(strlen($call['src']) == 4) {
							$info['dst'] = $call['dst'];
							$info['src'] = $call['src'];

						} elseif(strlen($call['dst']) == 4) {
							$info['dst'] = $call['dst'];
							$info['src'] = $call['src'];
						} elseif(strlen($call['cnum']) == 4) {
							$info['dst'] = $call['dst'];
							$info['src'] = $call['cnum'];
						} else {
							$info['dst'] = $call['dst'];
							$info['src'] = $call['src'];
						}
					break;
					case 'BUSY':
						$info['call_status'] = 397;
						if(strlen($call['src']) == 4) {
							$info['dst'] = $call['dst'];
							$info['src'] = $call['src'];

						} elseif(strlen($call['dst']) == 4) {
							$info['dst'] = $call['dst'];
							$info['src'] = $call['src'];
						} elseif(strlen($call['cnum']) == 4) {
							$info['dst'] = $call['dst'];
							$info['src'] = $call['cnum'];
						} else {
							$info['dst'] = $call['dst'];
							$info['src'] = $call['src'];
						}
					break;
				}

			break;

			case 'hangup':
				switch($call['dst']) {
					case 'STARTMEETME':
						$call['icons'][] = 'fa-users';
						$call['text'] = $call['src'] . ' ' . _('kicked from conference');
					break;
					case 'denied':
						$call['icons'][] = 'fa-ban';
						$call['text'] = $call['src'] . ' ' . _('denied by COS');
					break;
					default:
						if($call['src'] == $self) {
							$call['icons'][] = 'fa-arrow-right out';
							$call['icons'][] = 'fa-ban';
							$call['text'] = htmlentities($call['clid'],ENT_COMPAT | ENT_HTML401, "UTF-8");
						} elseif($call['dst'] == $self) {
							$call['icons'][] = 'fa-ban';
							$call['icons'][] = 'fa-arrow-left in';
							$call['text'] = htmlentities($call['clid'],ENT_COMPAT | ENT_HTML401, "UTF-8");
						} else {
							$call['text'] = _('Unknown') . ' (' . $call['uniqueid'] . ')';
						}
					break;
				}
			break;
			case 'congestion':
				switch($call['dst']) {
					case 'STARTMEETME':
						$call['icons'][] = 'fa-users';
						$call['text'] = $call['src'] . ' ' . _('kicked from conference');
					break;
					case 'denied':
						$call['icons'][] = 'fa-ban';
						$call['text'] = $call['src'] . ' ' . _('denied by COS');
					break;
					default:
						$info['call_status'] = 334;
						if(strlen($call['src']) == 4) {
							$info['dst'] = $call['dst'];
							$info['src'] = $call['src'];

						} elseif(strlen($call['dst']) == 4) {
							$info['dst'] = $call['dst'];
							$info['src'] = $call['src'];
						} elseif(strlen($call['cnum']) == 4) {
							$info['dst'] = $call['dst'];
							$info['src'] = $call['cnum'];
						} else {
							$info['dst'] = $call['dst'];
							$info['src'] = $call['src'];
						}

					break;
				}
			break;
			case 'playback':
				$info['dst'] = $call['dst'];
				$info['src'] = $call['src'];
			case 'background'://ivr呼入的
				$info['dst'] = $call['lastdata'];
				$info['src'] = $call['src'];
				$call['call_status']='ivr';
				$call['call_type'] = 'in';
			case 'waitexten'://ivr呼入的 提示按键，没按键的
				$info['dst'] = $call['dcontext'];
				$info['src'] = $call['src'];
				$call['call_status']='ivr';
				$call['call_type'] = 'in';
			break;
			case 'queue'://队列的
				if($call['disposition'] == "NO ANSWER"){
					$info['dst'] = $call['dst'];
					$info['src'] = $call['src'];
					$call['call_status']='q';
					$call['call_type'] = 'in';
					$call['billsec'] = 0;
					$info['recordingfile'] = $call['recordingfile'];
				}elseif($call['disposition'] == "BUSY"){
					$info['dst'] = $call['dst'];
					$info['src'] = $call['src'];
					$call['call_status']='q';
					$call['call_type'] = 'in';
					$call['billsec'] = 0;
					$info['recordingfile'] = $call['recordingfile'];
				}

			break;
			default:
				$info['dst'] = $call['dst'];
				$info['src'] = $call['src'];
		}
		//dump($call['call_type']);
		$info['id'] = $call['id'];
		$info['did'] = $call['did'];
		$info['call_status'] = $arr_call_status[$call['call_status']]['id'];	
		$info['call_type'] = $arr_call_type[$call['call_type']]['id'];		
		$info['call_time'] = strtotime($call['calldate']);
		$info['customer_id'] = $call['customer_id'];
		$info['user_id'] = $call['user_id'];
		$info['duration'] = $call['duration'];
		$info['billsec'] = $call['billsec'];
		$info['cid'] = $call['outbound_cnum'];	

		$arr[] = $info;
		
	}
	return $arr;
}

//验证号码格式是否正确
//在Cusomer和Leads 还有Contacts的Model类中会引用这个做验证
//zhangtuo 2016-5-2
function checkPhone($phone){
	$arr = getPhoneArray($phone);
	return $arr['success'];
}
//获取号码数组信息
//zhangtuo 2016-5-2
//
//return array
//如01052665935 外地固话
//array(4) {
//  ["success"] => bool(true) // 检查状态，ture表示是合法的号码
//  ["msg"] => string(12) "外地固话" //号码类型，或者错误提示
//  ["phone"] => string(10) "1052665935" //号码
//  ["phone_prefix"] => string(1) "0" //号码前缀 ，注意外地固话，前缀是0
//}
//  如 18500020086 手机号
//  array(4) {
//  ["success"] => bool(true)
//  ["msg"] => string(11) "11位手机"
//  ["phone"] => string(11) "18500020086"
//  ["phone_prefix"] => string(0) ""
//}
function getPhoneArray($phone){
	//定义一个返回的数组
	$arr = array("success"=>false,"msg"=>"","phone"=>"","phone_prefix"=>"");
	//去掉号码里面的空格和-字符
	$phone = trim(str_replace(' ','',str_replace('-','',$phone)));
	//检查一下是不是本地手机，这种情况是最常见的，放在最前面判断	
	if(preg_match("/^1[34578]{1}\d{9}$/",$phone)){  
	   $arr['success'] = true;
	   $arr['msg'] = "11位手机";
	   $arr['phone'] = $phone;
	   $arr['phone_prefix'] = NULL;
		return $arr; 
	//检查一下是不是外地手机，这种情况也比较常见
	}else if(substr($phone,0,1) == "0" && preg_match("/^1[34578]{1}\d{9}$/",substr($phone,1))){
	   $arr['success'] = true;
	   $arr['msg'] = "外地手机";
	   $arr['phone'] = substr($phone,1);
	   $arr['phone_prefix'] = "0";
		return $arr; 
	//这里要验证一下号码是不是数字的
	}else if(!is_numeric($phone)){
		$arr['msg'] = "号码格式错误,号码只能是数字";
		return $arr;
	//12位的检查
	}else if(strlen($phone) > 16 || strlen($phone) < 3){
		$arr['msg'] = "号码格式错误,号码位数应在3-16位之间";
		return $arr;
	//是不是本地固话,首位不为0，并且位数不大于8位
	}else if(substr($phone,0,1) != "0" && strlen($phone) <= 8){
	   $arr['success'] = true;
	   $arr['msg'] = "本地固话";
	   $arr['phone'] = $phone;
	   $arr['type'] = 'guhua';
	   $arr['phone_prefix'] = NULL;
		return $arr; 
	//外地固话，首位是0，第二位不是0
	}else if(substr($phone,0,1) == "0" && substr($phone,1,1) != "0"){
	   $arr['success'] = true;
	   $arr['msg'] = "外地固话";
	   $arr['phone'] = substr($phone,1);
	    $arr['type'] = 'guhua';
	   $arr['phone_prefix'] = "0";
		return $arr;
		//外地固话，首位是0，第二位是0 第三位不是0
	}else if(substr($phone,0,1) == "0" && substr($phone,1,1) == "0" && substr($phone,2,1) != "0"){
	   $arr['success'] = true;
	   $arr['msg'] = "港澳台固话";
	   $arr['phone'] = substr($phone,2);
	   $arr['type'] = 'guhua_gat';
	   $arr['phone_prefix'] = NULL;
		return $arr;
	}else if(strlen($phone) <15 || strlen($phone) >3){
	   $arr['success'] = true;
	   $arr['msg'] = "国际电话";
	   $arr['phone'] = $phone;
	   $arr['type'] = 'guoji';
	   $arr['phone_prefix'] = NULL;
		return $arr;
	}else{
		$arr['msg'] = $phone ."号码格式错误";
		return $arr;
	}
}

//号码查重
// zhangtuo 2016-5-2
// 检查是否有重复的号码，注意，$but_contacts_id 出去的id
// 有重复，或者号码错误，返回false;
// 没有重复，返回true;
function checkOnlyPhone($phone,$but_contacts_id =""){
	$phone_info = getPhoneArray($phone);
	//如果号码格式不对，返回错误
	if(!$phone_info['success']){
		return false;
	}else{
		$where = 'phone = '.$phone_info['phone'];
		if($but_contacts_id){
			$where .=" AND contacts_id !=".$but_contacts_id;
		}
		$r = D("Contacts")->where($where)->count();
		if($r){
			return false;//有重复
		}else{
			return true ;//没重复
		}
	}
}
/** 
* 获取某一模块对应的id
* 
* @access public
* @param  string  $module 模块名称,作为查询条件（必填） 
* @author wangchao  2016-04-21
* @return string
*/
function get_module_id($module){
	//$modules = M('system_module');
	//$where['module'] = array('eq',strtolower($module));
	//$module_id = $modules->where($where)->field('id')->find();
	$db           = Db::getInstance();
	$prefix       = C('DB_PREFIX');
	$systemModule = $db->query("SELECT id FROM ".$prefix."system_module WHERE module='".$module."';");
	unset($db);
	return $systemModule[0]['id'];
}



/** 
* 把某一模块的id转化为对应的模块名称
* 
* @access public
* @param  string  $module_id 模块id,作为查询条件（必填） 
* @author wangchao  2016-04-21
* @return string
*/
function get_module_name($module_id){
	$modules = M('system_module');
	$where['id'] = array('eq',$module_id);
	$module_name = $modules->where($where)->field('module')->find();
	return $module_name['module'];
}


/** 
* 获取选项类型的字段，生成一个二维数组，一位数组代表字段id，二位数组是 id对应的各个字段名 
* key是id
* @access public 
* @param  string  $module  模块的名称（必填）
* @param  string  $field   字段的名称（必填） 
* @author wangchao  2016-04-17
* @return array 
*/
function getOptionArray($module,$field){
	$module_id = get_module_id($module);
	//$where['module'] = array('eq',$module_id);
	//$where['field_en_name'] = array('eq',$field);
	//$field_id = M('field_option')->where($where)->field('field_id')->find();
	//$fields = M('field_option_value')->where('field_id='.$field_id['field_id'])->order('order_id')->select();
	$db       = Db::getInstance();
	$prefix   = C('DB_PREFIX');
	$field_id = $db->query("SELECT field_id FROM ".$prefix."field_option WHERE  module=$module_id AND field_en_name='$field'");
	$field_id = $field_id[0]['field_id'];
	$fields   = $db->query("SELECT*FROM ".$prefix."field_option_value WHERE field_id = '".$field_id."' ORDER BY order_id ASC;");
	unset($db);
	$arr = array();
	foreach( $fields as $v){
		$arr[$v['id']] = $v;
	}
	return $arr;
}

/** 
* 判断客户端ip地址是否在ip白名单列表中,存在返回true,否则返回false
* 
* @access public 
* @author wangchao  2016-07-04
* @return true/false
*/
function checkIpAllow(){
	$ip  = get_client_ip(); //获取客户端ip
	$ips = explode(',',C('bianliang._sys_allow_iplist')); //获取设置好的ip白名单列表
	if(in_array($ip,$ips)){
		return true;
	}else{
		return false;
	}
}

/** 
* 生成一个15位的、不会重复的随机数(bigint)，用于添加数据时 需要代替自增长id的地方，如添加字段
* 
* @access public 
* @author wangchao  2016-07-05
* @return bigint
*/
function bigintRandom(){
	$date   = date('Ymd'); //获取当前年月日(8位)
	$rand   = mt_rand(1000000,9999999); //随机生成一个7位数
	$bigint = $date.$rand; //加起来15位
	return $bigint;
}

/** 
* 获取选项类型的字段，生成一个二维数组，一位数组代表字段id，二位数组是 id对应的各个字段名 
* key是id
* @access public 
* @param  string  $module  模块的名称（必填）
* @param  string  $field   字段的名称（必填） 
* @author zhangtuo  2016-04-30
* @return array 
*/
function getFieldOptArray($module,$field_en_name="",$which_field_as_index=""){
	//如果模块不是数字，那么查找一下他的id
	if(!is_numeric($module)){
		$module_id = get_module_id($module);
	}else{
		$module_id = $module;
	}
	$where['module'] = array('eq',$module_id);
	//如果which_fiedld_as_index是空，那就用id作为返回数组的索引
	$which_field_as_index = $which_field_as_index == "" ? "id" :$which_field_as_index;
	//field_en_name 不为空，那就返回这个字段的
	if($field_en_name !=""){
		$where['field_en_name'] = array('eq',$field_en_name);
		$field_id = M('field_option')->where($where)->field('field_id')->find();
		$fields = M('field_option_value')->where('field_id='.$field_id['field_id'])->order('order_id')->select();
		$arr = array();
		foreach( $fields as $v){
			$v['field_value'] = L($v['field_value']);
			$arr[$v[$which_field_as_index ]] = $v;
		}
		return $arr;
	
	//field_en_name 为空，那就返回这个模块的所有字段的多维数组
	//各个字段的field_en_name 作为第一维度的索引
	}else{
		//获取这个模块所有的选项类型字段
		$field_en_name_list = M('field_option')->where($where)->field('field_en_name')->select();
		$arr = array();
		foreach($field_en_name_list as $v){
			$v['field_value'] = L($v['field_value']);
			$arr[$v['field_en_name']] = getFieldOptArray($module_id,$v['field_en_name'],$which_field_as_index);
		}
		return $arr;
	}
}

/*array_column兼容低版本*/
if( ! function_exists('array_column'))
{
  function array_column($input, $columnKey, $indexKey = NULL)
  {
    $columnKeyIsNumber = (is_numeric($columnKey)) ? TRUE : FALSE;
    $indexKeyIsNull = (is_null($indexKey)) ? TRUE : FALSE;
    $indexKeyIsNumber = (is_numeric($indexKey)) ? TRUE : FALSE;
    $result = array();
 
    foreach ((array)$input AS $key => $row)
    { 
      if ($columnKeyIsNumber)
      {
        $tmp = array_slice($row, $columnKey, 1);
        $tmp = (is_array($tmp) && !empty($tmp)) ? current($tmp) : NULL;
      }
      else
      {
        $tmp = isset($row[$columnKey]) ? $row[$columnKey] : NULL;
      }
      if ( ! $indexKeyIsNull)
      {
        if ($indexKeyIsNumber)
        {
          $key = array_slice($row, $indexKey, 1);
          $key = (is_array($key) && ! empty($key)) ? current($key) : NULL;
          $key = is_null($key) ? 0 : $key;
        }
        else
        {
          $key = isset($row[$indexKey]) ? $row[$indexKey] : 0;
        }
      }
 
      $result[$key] = $tmp;
    }
 
    return $result;
  }
}

/**
*  getUserIdsByDepId
*  根据
*  @access  public
*  @param   string $dep_id,部门ID或者标识符,self_d
*  @author  qiandongjun@southtel.cn
*  @date    2016-12-01
*  @return  string
*  @example getUserIdsByDepId('1,2,3,4') => 111,112,113
*/
function getUserIdsByDepId($dep_id,$col="department_id")
{
	$dep_id = !$dep_id || $dep_id == 'self_d' ? session('department_id') : $dep_id;
	$MUser  = M('user');
	if(!$dep_id)
	{
	  $user_ids = array();
	}elseif(strpos($dep_id,',') !== false){
	  $user_ids=$MUser->where($col.' in ('.$dep_id.')')->getField('user_id',true);
	}else{
	  $user_ids=$MUser->where($col.' = \''.$dep_id.'\'')->getField('user_id',true);
	}
	if(is_array($user_ids))
	{
	  $user_ids = implode(',',$user_ids);
	}
	return $user_ids;
}

/**
*  getManageDepList
*  获取某个角色的管理范围
*  @access  public
*  @param   int $role_id,角色ID
*  @author  qiandongjun@southtel.cn
*  @date    2016-12-01
*  @return  string
*  @example getManagerDepList(1) => all
*/
function getManageDepList($role_id)
{
  if(!$role_id)
  {
	$role_id = session('role_id');  
  }
  $dep_list  = M('role')->where('role_id = %d',$role_id)->getField('department_list');
  return $dep_list;
}
/**
*  viewManageFilter
*  根据角色的管理范围生成对应的SQL
*  @access  public
*  @param   string $user_col,用户id的字段名,$dep_col,用户部门的字段名,$type 返回的数据类型, 
*  @author  qiandongjun@southtel.cn
*  @date    2016-12-01
*  @return  string
*  @example type String viewManageFilter('user_id') => d_id = 1
            type Array  viewManageFilter('user_id','d_id','Array') => array('d_id'=>1)
*/
function viewManageFilter($user_col="user_id",$dep_col="d_id",$type='String',$not_have_dep_id=false)
{
    if($type == 'String')
	{
	 $where = "";
	}else{
	 $where = array();	
	}
	$d_list = session('manage_dep_list');
	if($not_have_dep_id)
	{
	  $user_ids = getUserIdsByDepId($d_list);
	}
	switch($d_list)
	{ 
	   case 'all':
	   break;
	   case 'self':
	     if(is_array($where))
		 {
		  $where[$user_col] = session('user_id');
		 }else{
	      $where = " AND ".$user_col." = ".session('user_id');
	     }
	   break;
	   case 'self_d':
	     if(is_array($where) && !$not_have_dep_id)
		 {
		   $where[$dep_col] = session('department_id');
		 }elseif(is_array($where) && $not_have_dep_id){
		   $where[$user_col] = array('in',$user_ids);
		 }elseif($not_have_dep_id){
		   $where = " AND ".$user_col." in (".$user_ids.")";
		 }else{
	       $where = " AND ".$dep_col."  = ".session('department_id');
		 }
	   break;
	   default:
	     if(strpos($d_list,',') >= 0 && is_array($where) && !$not_have_dep_id)
		 {
		    $where[$dep_col]  = array('in',$d_list); 
		 }elseif(strpos($d_list,',') >= 0 && is_array($where)){
		    $where[$user_col] = array('in',$user_ids);
		 }elseif(strpos($d_list,',') >= 0 && !$not_have_dep_id){
		    $where = " AND ".$dep_col." in (".$d_list.")";
		 }elseif(strpos($d_list,',') >= 0){
		    $where = " AND ".$user_col." in (".$user_ids.")";
		 }elseif(is_array($where) && !$not_have_dep_id){
			$where[$dep_col]  = $d_list;
		 }elseif(is_array($where)){
			$where[$user_col] = array('in',$user_ids);
		 }elseif($not_have_dep_id){
			$where = " AND ".$user_col." in (".$user_ids.")";
		 }else{
			$where = " AND ".$dep_col." = ".$d_list;
		 }
	   break;	
	}
	return $where;
}

/** 
* getRoleActionList 
* 获取某个角色的action_code 数组 
* 
* @access public 
* @param int $role_id 角色ID，可以为空，如果是空就从session里获取 
* @author      luckytuo@gmail.com
* @date        2016-4-25
* @return array 
*  如 array(2) {
    [0] => string(8) "customer"
    [1] => string(13) "customer_edit"
  }
*/  
function getRoleActionList($role_id=""){
	if(empty($role_id) ){
		$role_id = session('role_id');
	}
	$str = M('role')->where('role_id = %d',$role_id)->field('action_list')->find();
	$str = $str['action_list'];
	$str = str_replace(" ","",$str);
	$str = trim($str,',');
	$arr = M('Action')->where('action_id in(%s)',$str)->field('action_code')->order('order_id')->select();
	return array_column($arr,'action_code');
}
/* authCheck 
* auth权限验证
* @access public 
* @param string $action_code 权限项目码
* @param bool $is_die 当没有权限时，是否立刻终止，默认是不终止，只返回flase；
* @author      luckytuo@gmail.com
* @date        2016-4-25
* @return bool 或 直接终止
*/  
function authCheck($action_code,$is_die = false){	
	if(empty($action_code)){
		if(!$is_die){
			return false;
		}else{
			die('非法授权');
		}
	}
	//如果是管理，就免检
	if(session('?admin')){
		return true;
	}	
	if(in_array($action_code, session('action_code_list'))){		
		return true;	
	}else{
		if(!$is_die){
			return false;
		}else{
			die('非法授权');
		}
	}
}



/**
* 计算回收时间
*
* @param string $msg_type  success,error,info,warning,
* @param string $msg_title  标题 必填
* @param string $msg_text  小字
* @param string $msg_more  详细信息，带滚动条的
* @return arrary 数组
* @author  zhangtuo 2015-10-11
*/
function sys_msg($msg_type,$msg_title,$msg_text="",$msg_more = ""){
	$arr = array(
		'msg_title' => $msg_title,
		'msg_text'	=> $msg_text,
		'msg_more'	=> $msg_more,
	);
	switch($msg_type)
	{
		case "success":
			$arr['msg_type'] ="success";
			break;
		case "error":
			$arr['msg_type'] ="error";
			break;
		case "info":
			$arr['msg_type'] ="info";
			break;
		case "warning":
			$arr['msg_type'] ="warning";
			break;
		default:
			$arr['msg_type'] ="info";			
	}
	return $arr;

}



/**
* 计算回收时间
*
* @param int $sea_id  公海池id
* @param int $customer_id 客户id 
* @return int 时间戳
* @author  jinzhihui 2016-6-17
*两参数可以为空，但不可同时为空
*如果所传参数为customer_id，则第一个参数必须指定为空
*
*/
function getEndTime($sea_id = '',$customer_id = ''){
	if (empty($customer_id) && empty($sea_id)) {
		return false;
	}elseif ($sea_id == '') { //传的参数为customer_id
		$m = M('Customer');
		$sea = $m->where('customer_id=%d',$customer_id)->field('sea_id,genjin_time')->find();
		$sea_id = $sea['sea_id'];
	}
	$t = time();
	$arr = M('sea')->where('sea_id='.$sea_id)->find();
	//回收规则为手动
	if($arr['recycle_rule'] == 1){ 
		return 0; 
	}else{ //回收规则为系统自动回收
		$t1 = $t + $arr['no_log_day']*86400;
		$t2 = $t + $arr['no_next_log_day']*86400;
		if ($arr['no_log_day'] > 0 && $arr['no_next_log_day'] > 0 ) {
			if($sea['genjin_time'] > 0){
				return $t2;
			}else return $t1;
		}elseif ($no_log_day > 0) {
			return $t2;
		}else return $t1;
	}
}

//获取相对时间，传参可以是日期 如 "2015-6-16 12:10:10"; ，也可以是时间戳 
function getDiffTime($time) {
	if($time == 0 || $time == ""){
		return "";
	}
	if(is_numeric($time)){
		$diff = time() - $time;
	}else{
    	$diff = time() - strtotime($time);
	}
	if($diff > 0 ){
		if ($diff<60)
			return sprintf(L('DIFF_TIME_MINUTE_AGO'),$diff);
		$diff = round($diff/60);
		if ($diff<60)
			return sprintf(L('DIFF_TIME_SECOND_AGO'),$diff);
		$diff = round($diff/60);
		if ($diff<24)
			return sprintf(L('DIFF_TIME_HOUR_AGO'),$diff);
		$diff = round($diff/24);
		if ($diff<7)
			return sprintf(L('DIFF_TIME_DAY_AGO'),$diff);
		$diff = round($diff/7);
		if ($diff<4)
			return sprintf(L('DIFF_TIME_WEEK_AGO'),$diff);
	}else{
		$diff = abs($diff);
		if ($diff<60)
			return sprintf(L('DIFF_TIME_MINUTE_AFTER'),$diff);
		$diff = round($diff/60);
		if ($diff<60)
			return sprintf(L('DIFF_TIME_SECOND_AFTER'),$diff);
		$diff = round($diff/60);
		if ($diff<24)
			return sprintf(L('DIFF_TIME_HOUR_AFTER'),$diff);
		$diff = round($diff/24);
		if ($diff<7)
			return sprintf(L('DIFF_TIME_DAY_AFTER'),$diff);
		$diff = round($diff/7);
		if ($diff<4)
			return sprintf(L('DIFF_TIME_WEEK_AFTER'),$diff);
	}
	
	
	if(is_numeric($time)){
		return date('Y-m-d',$time);
	}else{
		return date("Y-m-d", strtotime($time));
	}
}
function deldir($dir) {
    $dh = opendir($dir);
    while ($file = readdir($dh)) {
        if ($file != "." && $file != "..") {
            $fullpath = $dir . "/" . $file;
            if (!is_dir($fullpath)) {
                @unlink($fullpath);
            } else {
                @deldir($fullpath);
            }
        }
    }
    closedir($dh);
}

//手机端选择负责人
function owner_name_select($role_id){
	$d_role_view = D('RoleView');
		
	$all_role = M('role')->where('user_id <> 0')->select();
	$below_role = getSubRole(session('role_id'), $all_role);

	$below_ids[] = session('role_id');
	foreach ($below_role as $key=>$value) {
		$below_ids[] = $value['role_id'];
	}
	$where = 'role.role_id in ('.implode(',', $below_ids).')';
	
	$role_list = $d_role_view->where($where)->order('department_id ASC,role_id ASC')->field('role_id,user_name,department_name,role_name')->select();
	
	$string = '<select id="owner_role_id" name="owner_role_id">';
	if(is_array($role_list)){
		$string .= '<option value="0">--请选择--</option>';
		foreach($role_list as $v){
			if($role_id && $role_id == $v['role_id']){
				$string .= '<option selected="selected" value="'.$v['role_id'].'">'.$v['user_name'].'</option>';
			}else{
				$string .= '<option value="'.$v['role_id'].'">'.$v['user_name'].'</option>';
			}			
		}		
	}
	$string .= '</select>';
	return $string;
}


//高级搜索生成where条件
function field($search,$condition=''){
	switch ($condition) {
		case "is" : $where = array('eq',$search);break;
		case "isnot" :  $where = array('neq',$search);break;
		case "contains" :  $where = array('like','%'.$search.'%');break;
		case "not_contain" :  $where = array('notlike','%'.$search.'%');break;
		case "start_with" :  $where = array('like',$search.'%');break;
		case "not_start_with" :  $where = array('notlike',$search.'%');break;
		case "end_with" :  $where = array('like','%'.$search);break;
		case "is_empty" :  $where = array('eq','');break;
		case "is_not_empty" :  $where = array('neq','');break;
		case "gt" :  $where = array('gt',$search);break;
		case "egt" :  $where = array('egt',$search);break;
		case "lt" :  $where = array('lt',$search);break;
		case "elt" :  $where = array('elt',$search);break;
		case "eq" : $where = array('eq',$search);break;
		case "neq" : $where = array('neq',$search);break;
		case "between" : $where = array('between',array($search-1,$search+86400));break;
		case "nbetween" : $where = array('not between',array($search,$search+86399));break;
		case "tgt" :  $where = array('gt',$search+86400);break;
		default : $where = array('eq',$search);
	}
	return $where;
}

function format_price($num){
	$num = round($num, 0);
	$s_num = strval($num);
	$len = strlen($s_num)-1;
	$result = round($num, -$len);
	return $result;
}

//方法说明	获取某个model的所有字段已经公共字段信息，并指定索引
function getAllFields($model,$key="field"){
    if(!$model) return false;
    $modules = get_module_id(strtolower($model));
	$where = " is_main = 1 AND in_index=1 AND model ='".$modules."'";
	$list = M('Fields')->where($where)->order('order_id ASC')->select();
	//out($list);
	//out(M('Fields')->getLastSql());
	$model_fields = array();
	foreach($list as $v){
		$v['name'] = L($v['name']);
		$model_fields[$v[$key]] = $v;
	}
	//out($model_fields);
	return $model_fields;
}
//方法说明	获取首页需要显示的列名字符串
function getIndexFields($model){
    if(!$model) return false;
    $modules = get_module_id(strtolower($model));
	//$m_model = M($model);
	//$where['in_index'] = 1;
	//$where['model'] = $model;
	//$where = " in_index=1 AND (model ='".$model."' OR model='')";
	if($model == "leads" ){
		//$where = "( in_index=1 AND model ='".$model."')  OR ( model='' AND field in('owner_role_id','creator_role_id','create_time','update_time'))";
		$where = "( in_index=1 AND is_main = 1 AND model ='".$modules."')  OR ( model='' AND field in('owner_role_id','creator_role_id','create_time','update_time','log_time'))";
	}else{
		$where['in_index'] = 1;
		$where['model'] = $modules;
	}
	$model_fields = M('Fields')->where($where)->order('order_id ASC')->select();
	//dump(M('Fields')->getLastSql());
	return $model_fields;
}
//获取主表字段 用于搜索
function getMainFields($model){
	if(!$model) return false;
	$modules = get_module_id(strtolower($model));
	//$m_model = M($model);
	$where['is_main'] = 1;
	$where['model'] = $modules;
	$model_fields = M('Fields')->where($where)->order('order_id ASC')->select();
	return $model_fields;
}
//获取所有主表的字段
function getAllFieldsAbs($model,$k='field')
{
	$modules = get_module_id(strtolower($model));	
    //$list = M('fields')->where('model = "'.$modules.'" and is_main=1')->order('order_id')->select();
	$db     = Db::getInstance();
	$prefix = C('DB_PREFIX');
	$list   = $db->query("SELECT*FROM ".$prefix."fields WHERE model='".$modules."' AND is_main = 1 ORDER BY order_id ASC");
	unset($db);
	$field_list_all = array();
	foreach($list as $v){
		$v['name'] = L($v['name']);
		$field_list_all[$v[$k]] = $v;
	}
	return $field_list_all;
}
//获取所有主表的字段
function getAllFieldsAbsCustomer($model,$k='field')
{
	$modules = get_module_id(strtolower($model));	
    //$list = M('fields')->where('model = "'.$modules.'" and is_main=1')->order('order_id')->select();
	$db     = Db::getInstance();
	$prefix = C('DB_PREFIX');
	$list   = $db->query("SELECT*FROM ".$prefix."fields WHERE model='".$modules."' AND is_main = 1 AND in_export=1 ORDER BY order_id ASC");
	unset($db);
	$field_list_all = array();
	foreach($list as $v){
		$v['name'] = L($v['name']);
		$field_list_all[$v[$k]] = $v;
	}
	return $field_list_all;
}
/**获取用户自定义的显示信息
 * $modle 类型
 * $param_name 参数
 * $text 附加信息
 * 2013-10-23
 **/
function getUserCol($model)
{
	$modle_r_id = get_module_id(strtolower($model));
	//dump($modle_r_id);
	$m_user_col = M('user_cols')->where(' type = '.$modle_r_id.' AND user_id = '.session('user_id'))->order('order_id ASC')->select();
	$row = array();
	foreach($m_user_col as $val)
	{
	  $row[$val['field_id']] = $val['order_id'];
	}
	return count($row) > 0 ? $row : false;
}
/**
 * 处理隐藏排序
 * $type 类型  $field_list 原先的filed $field_all_list 所有的feild
 * $param_name 参数
 * 2013-10-23
 **/
function handleUserCol($type,$field_list,$field_all_list)
{
	$user_custom_col     = getUserCol($type);
	$page_show_field     = array();
	$field_all_list_byId = array();
	$field_list_byId     = array();
	foreach($field_all_list as $val)
	{   $val['name'] =L($val['name']);
	  	$field_all_list_byId[$val['field_id']] = $val;
	}
	if(!$user_custom_col)
	{
	  $page_show_field = $field_list;
	  $page_hide_field = array_diff_key($field_all_list,$field_list);
	}elseif(is_array($user_custom_col)){
	  $page_hide_field = array_diff_key($field_all_list_byId,$user_custom_col);
	  foreach($user_custom_col as $field_id=>$order_id)
	  {
		array_push($page_show_field,$field_all_list_byId[$field_id]); 
	  }
	}	
   return array('show'=>$page_show_field,'hide'=>$page_hide_field);
}
/**记录操作日志
 * $id 操作对象id
 * $param_name 参数
 * $text 附加信息
 * 2013-10-23
 **/
function actionLog($id,$param_name='',$text=''){
    $role_id = session('role_id');
    $user = M('user')->where(array('user_id'=>session('user_id')))->find();
    $category = $user['category_id'] == 1 ? L('ADMIN') : L('USER');
    $data['role_id'] = $role_id;
    $data['module_name'] = strtolower(MODULE_NAME);
    $data['action_name'] = strtolower(ACTION_NAME);		
	if(!empty($param_name)){
		$data['param_name'] = strtolower($param_name);
	}
    $data['create_time'] = time();
    $data['action_id'] = $id;
    $data['content'] = L('ACTIONLOG',array($category,$user['name'],date('Y-m-d H:i:s'),L(ACTION_NAME),$id,L(MODULE_NAME),$text));
    $actionLog = M('actionLog');
    $actionLog->create($data);
    if($actionLog->add()){
		//如果是删除操作，设置action_delete = 1
		if(strtolower(ACTION_NAME) == 'delete' || strtolower(ACTION_NAME) == 'completedelete' || strtolower(ACTION_NAME) == 'log_delete'){
			$actionLog->where('module_name = "%s" and action_id = %d', strtolower(MODULE_NAME), $id)->setField('action_delete',1);
		}
		return true;
	}else{
		return false;
	}
}
function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true) {
    if(function_exists("mb_substr"))
        $slice = mb_substr($str, $start, $length, $charset);
    elseif(function_exists('iconv_substr')) {
        $slice = iconv_substr($str,$start,$length,$charset);
        if(false === $slice) {
            $slice = '';
        }
    }else{
        $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
        $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
        $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
        $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
        preg_match_all($re[$charset], $str, $match);
        $slice = join("",array_slice($match[0], $start, $length));
    }
	if(utf8_strlen($str) < $length) $suffix = false;
    return $suffix ? $slice.'...' : $slice;
}

function utf8_strlen($string = null) {
	preg_match_all("/./us", $string, $match);
	return count($match[0]);
}

function getDateTime($model){		
	$user = M('User')->where('role_id = %d',session('role_id'))->field('user_id,last_read_time')->find();		
	if($user['last_read_time']){
		$last_read_time = json_decode($user['last_read_time'],true);			
	}
	$last_read_time[$model] = time();	
	$last_read_time = json_encode($last_read_time);		
	M('User')->where('user_id = %d',$user['user_id'])->setField('last_read_time',$last_read_time);
	return true;
}

function getSubCategory($category_id, $category, $separate) {
	$array = array();
	foreach($category AS $value) {
		if ($category_id == $value['parent_id']) {
			$array[] = array('category_id' => $value['category_id'], 'name' => $separate.$value['name'],'description'=>$value['description']);
			$array = array_merge($array, getSubCategory($value['category_id'], $category, $separate.'--'));
		}
	}
	return $array;
}

// 获取工单分组的HTML  wangchao   2016-8-23
function getGroupListHtml($id,$name="",$select_id="") {
	$list = getGroupList();
	$str = '<select id="'.$id.'" name="'.$name.'" class="form-control">';
	foreach($list as $v){
		if($v['group_id'] == $select_id){
			$str .='<option value="'.$v['group_id'].'"  selected="selected" >'.L($v['group_name']).'</option>';
		}else{
			$str .='<option value="'.$v['group_id'].'" >'.L($v['group_name']).'</option>';
		}
	}
	$str .='</select>';
	return $str;
}

// 获取工单业务分组array，which_field_as_index是索引。默认是group_id
function getGroupList($which_field_as_index ="group_id") {
	$list = M('group')->order('order_id')->select();	
	$arr = array();

	foreach($list as $v){
		$arr[$v[$which_field_as_index]] = $v;
	}
	//dump($arr);
	return $arr;
}


// 获取公海分组的HTML
function getSeaListHtml($id,$name="",$select_id="") {
	$list = getSeaList() ;
	$str = '<select id="'.$id.'" name="'.$name.'" class="form-control">';
	foreach($list as $v){
		if($v['sea_id'] == $select_id){
			$str .='<option value="'.$v['sea_id'].'"  selected="selected" >'.L($v['sea_name']).'</option>';
		}else{
			$str .='<option value="'.$v['sea_id'].'" >'.L($v['sea_name']).'</option>';
		}
	}
	$str .='</select>';
	return $str;
}


// 获取公海分组array，which_field_as_index是索引。默认是sea_id
// zhangtuo 2016-4-30
function getSeaList($which_field_as_index ="sea_id") {
	$list = M('sea')->where('is_private = 0')->order('order_id')->select();	
	$arr = array();

	foreach($list as $v){
                 $v['sea_name'] = L($v['sea_name']);
		$arr[$v[$which_field_as_index]] = $v;
	}
	//dump($arr);
	return $arr;
}

// 获取部门分组array，key是部门ID
// zhangtuo 2016-4-30
function getDepList($which_field_as_index ="department_id") {
	$list = M('Department')->select();
	foreach ($list as $k => $v) {
		$v['name'] = L($v['name']);
			$de_list[] = $v;
		}	
	$arr = array();
	$arr[0]=array("name"=>"全公司");
	foreach($de_list as $v1){
		$arr[$v1[$which_field_as_index]] = $v1;
	}
	//dump($arr);
	return $arr;
}
// 获得所有的排班分组
// qiandongjun  2016-12-14
function getArrangeGroup()
{
  $list = M('ArrangeGroup')->field('group_id,group_name')->select();
  $res  = array();
  foreach($list as $v){
	$res[$v['group_id']] = $v['group_name'];  
  }
  return $res;
}

// 获取用户分组array，默认key是user_id
// wangchao  2016-07-07
function getUserList($which_field_as_index ="user_id") {
	$list = M('User')->field('user_id,name,account,status,department_id')->select();	
	$arr = array();
	foreach($list as $v){
		if($v['status'] == 0){
			$v['name'] = $v['name'].'(已离职)';
		}
		$arr[$v[$which_field_as_index]] = $v;
	}
	return $arr;
}

// 获取客户分组array，默认key是customer_id
// wangchao  2016-07-08
function getCustomerName($which_field_as_index ="customer_id") {
    $list = M('Customer')->field('customer_id,is_deleted,name')->select(); 
    $arr = array();
    foreach($list as $v){
    	if($v['is_deleted'] == 1){
			$v['name'] = $v['name'].'(已删)';
		}
        $arr[$v[$which_field_as_index]] = $v;
    }
    //dump($arr);
    return $arr;
}
// 获取运营商array，暂时不用
//  whh 2016-11-09
function getCorpName($which_field_as_index ="corp_id") {
   $list = getOptionArray('phoneGsd', 'phone_corp');
    $arr = array();
    foreach($list as $v){
        $arr[$v[$which_field_as_index]] = $v;
    }
    //dump($arr);
    return $arr;
}
// 获取质检标签array，
//  whh 2016-11-11
function getQcType($which_field_as_index ="id") {
   $list = getOptionArray('qc', 'qc_type');
    $arr = array();
    foreach($list as $v){
        $arr[$v[$which_field_as_index]] = $v;
    }
    $arr[0] = array( 'id' => 0,
                     'field_value' => '其他');
    return $arr;
}
// 获取运营商
// whh 2016-10-26
/*function getCorpName($corp_id) {
	$list = getOptionArray('phoneGsd', 'phone_corp');
	foreach($list as $k => $v){
		if($v['field_id'] == $corp_id){
          $corp_name = $v['field_value'];
		}
		
	}
	//dump($arr);
	return $corp_name;
}*/
// 获取部门的HTML
function getSubDepartmentHtml($id,$name="",$select_id="") {
	$department = M('Department');
	$department_list = $department->select();	
	$d_list = getSubDepartment(0,$department_list);
	//dump($d_list);
	//dump($id);
	$str = '<select id="'.$id.'" name="'.$name.'" class="form-control"><option value="0">全公司</option>';
	foreach($d_list as $v){
		if($v['department_id'] == $select_id){
			$str .='<option value="'.$v['department_id'].'"  selected="selected" >'.L($value['name']).'</option>';
		}else{
			$str .='<option value="'.$v['department_id'].'" >'.L($value['name']).'</option>';
		}
	}
	$str .='</select>';
	return $str;
}
// 不包括自己所在部门
function getSubDepartment($department_id, $department, $separate, $no_separater) {
	$array = array();
	if($no_separater){
		foreach($department AS $value) {
			if ($department_id == $value['pid']) {
				$array[] = array('department_id' => $value['department_id'], 'name' => $separate.L($value['name']),'description'=>$value['description']);
				$array = array_merge($array, getSubDepartment($value['department_id'], $department, $separate, 1));
			}
		}
	}else{
		foreach($department AS $value) {
			if ($department_id == $value['pid']) {
				$array[] = array('department_id' => $value['department_id'], 'name' => $separate.L($value['name']),'description'=>$value['description']);
				$array = array_merge($array, getSubDepartment($value['department_id'], $department, $separate.' ▶ '));
			}
		}
	}
	return $array;
}

//包括自己所在部门
function getSubDepartment2($department_id, $department, $first=0) {
	$array = array();
	$m_department =  M('role_department');
	if($first == 1){
		$depart = $m_department->where('department_id = %d', session('department_id'))->find();
		$array[] = array('department_id'=>$depart['department_id'],'name'=>$depart['name'], 'description'=>$depart['description']);
	}
	foreach($department AS $value) {
		if ($department_id == $value['pid']) {
			$array[] = array('department_id' => $value['department_id'], 'name' => $separate.$value['name'],'description'=>$value['description']);
			$array = array_merge($array, getSubDepartment2($value['department_id'], $department, '--'));
		}
	}
	return $array;
}

function getSubDepartmentTreeCode($department_id, $first=0) {
	$string = "";
	$department_list = M('Department')->where('pid = %d', $department_id)->select();
	$position_list = M('role')->where('department_id = %d', $department_id)->select();

	if ($department_list || $position_list) {
		if ($first) {
			$string = '<ul id="browser" class="filetree">';
		} else {
			$string = "<ul>";
		}
		

		foreach($position_list AS $value) {
			$string .= "<li><span rel='".$value['role_id']."' class='file'>".L($value['name'])." &nbsp; <span class='control' id='control_file".$value['role_id']."'><a class='position_edit' rel=".$value['role_id']." href='javascript:void(0)'>".L('EDIT')."</a> &nbsp; <a class='position_delete' rel=".$value['role_id']." href='javascript:void(0)'>".L('DELETE')."</a> </span> </span></li>";
		}
		foreach($department_list AS $value) {
			//if($first){
				$string .= "<li><span rel='".$value['department_id']."' class='folder'>".L($value['name'])." &nbsp; <span class='control' id='control_folder".$value['department_id']."'><a class='department_edit' rel=".$value['department_id']." href='javascript:void(0)'>".L('EDIT')."</a> &nbsp; <a class='department_delete' rel=".$value['department_id']." href='javascript:void(0)'>".L('DELETE')."</a> </span></span>".getSubDepartmentTreeCode($value['department_id'])."</li>";
			/*} else {
				$string .= "<li class='closed'><span rel='".$value['department_id']."' class='folder'>".$value['name']." &nbsp; <span class='control' id='control_folder".$value['department_id']."'><a class='department_edit' rel=".$value['department_id']." href='javascript:void(0)'>".L('EDIT')."</a> &nbsp; <a class='department_delete' rel=".$value['department_id']." href='javascript:void(0)'>".L('DELETE')."</a> </span></span>".getSubDepartmentTreeCode($value['department_id'])."</li>";
			}*/
			
		}
		$string .= "</ul>";
	} 

	return $string;
}

//type == 1获取授权完整树形图
//type == 2获取选择授权树形图
function getSubPositionTreeCode($role_id, $first=0,  $type=1) {
	$string = "";
	$position_list = M('role')->where('pid = %d', $role_id)->select();
	//dump($position_list);
	//exit;
	if ($position_list) {
		if ($first) {
			if($type == 1)
				$string = '<ul id="browser" class="filetree">';
			else 
				$string = '<ul class="filetree">';
		} else {
			$string = "<ul>";
		}
		foreach($position_list AS $value) {
			$department_name = M('Department')->where('department_id = %d', $value['department_id'])->getField('name');
			$department_name =L($department_name);
			$user_list = D('RoleView')->where('role.role_id = %d', $value['role_id'])->select();
			//dump(D('RoleView')->getlastsql());
			//exit;
			$user_str = '';
			foreach($user_list as $v){
				if($v['status'] == '0'){
					$username = '<del>'.$v['user_name'].'</del>';
				}else{
					$username = $v['user_name'];
				}
				//$user_str .= '<a style="color: #000000;" href="'.U('user/view','id='.$v['user_id']).'" target="_blank">'.$username.'、</a>';
				if($username){
					$user_str .= '<a style="color: #000000;"  target="_blank">'.$username.'、</a>';
				}
				
			}
			if($user_str) $user_str = '('.$user_str.')';
			
			if($type == 1){
				$link_str = " <span class='control' id='control_file".$value['role_id']."'> <a class='position_edit' rel=".$value['role_id']." href='javascript:void(0)'>".L('EDIT')."</a> &nbsp; <a class='permission' rel=".$value['role_id']." href='javascript:void(0)'>".L('AUTHORIZE')."</a>&nbsp;&nbsp; <a class='derolesetting' rel=".$value['role_id']." href='javascript:void(0)'>".L('DEPARTMENT_MG')."</a>&nbsp;  &nbsp; <a class='position_delete' rel=".$value['role_id']." href='javascript:void(0)'>".L('DELETE')."</a></span>";
			}else{
				//$link_str = " <span class='control' id='control_file".$value['role_id']."'> <a class='allow_permission_id' rel=".$value['role_id']." href='javascript:void(0)'>".'选择'."</a> ";
				$link_str = " <span class='control' id='control_file".$value['role_id']."'> <input class='allow_permission_id' type='radio' name='parent_id' rel=".$value['role_id']." href='javascript:void(0)'>";
			}
			
			$string .= "<li style='list-style-type: none;'><span rel='".$value['role_id']."' class='file'>".L($value['name'])." - $department_name"." &nbsp; ".$user_str." &nbsp;".$link_str."</span>".getSubPositionTreeCode($value['role_id'], 0, $type)."</li>";
			
		}
		$string .= "</ul>";
	} 

	return $string;
}

//参数说明
//$role_id == 0 为当前人下属roleid
//$role_id == 1 为获得所有人roleid
function getSubRoleId($self = true, $role_id=0){
	$all_role = M('role')->where('user_id <> 0')->select();
	if(!$role_id){
		$role_id = session('role_id');
		$below_role = getSubRole($role_id, $all_role);
	}else{
		$below_role = getSubRole(0, $all_role);
	}
	
	$below_ids = array();
	if ($self) {
		$below_ids[] = $role_id;
	}
	foreach ($below_role as $key=>$value) {
		$below_ids[] = $value['role_id'];
	}
	return array_unique($below_ids);
}

/*
*	手机端getSubRoleId
*/
function getSubRoleByRole($role_id,$self = true){
	$all_role = M('role')->where('user_id <> 0')->select();
	$below_role = getSubRole($role_id, $all_role);
	$below_ids = array();
	if ($self) {
		$below_ids[] = $role_id;
	}
	foreach ($below_role as $key=>$value) {
		$below_ids[] = $value['role_id'];
	}
	return $below_ids;
}


function getSubRole($role_id, $role_list, $separate) {
	$d_role = D('RoleView');
	if($d_role->where('role.role_id = %d', $role_id)->find()){
		$role_id = $d_role->where('role.role_id = %d', $role_id)->getField('role_id');
	}else{
		$role_id  = 0;
	}
	$sub_position = getPositionSub($role_id ,true);
	foreach($sub_position AS $role_id) {
		$son_role = $d_role->where('role.role_id = %d', $role_id['role_id'])->select();
		foreach($son_role as $val){
			$array[] = array('role_id' => $val['role_id'],'user_id' => $val['user_id'], 'pid' => $val['pid'], 'name' => $separate . $val['department_name'] . ' | ' . $val['role_name']);
		}
	}
	return $array;
}

function getPositionSub($role_id ,$sub = false){
	$sub_position = M('role')->where('pid = %d', $role_id)->select();
	$array = $sub_position;
	if($sub){
		foreach($sub_position as $value){
			$son_position = getPositionSub($value['role_id'] ,$sub);
			if(!empty($son_position)){
				$array = array_merge($array, $son_position);
			}
		}
	}
	return $array;
}

function getSubPosition($role_id, $position, $separate) {
	$array = array();
	foreach($position AS $key=> $value) {
		if ($role_id == $value['pid']) {
			$m_department = M('Department');
			$department_name = $m_department->where('department_id = %d', $value['department_id'])->getField('name');
			$array[] = array('role_id' => $value['role_id'], 'name' => $separate . $department_name . ' | ' . $value['name'],'description'=>$value['description']);
			$array = array_merge($array, getSubPosition($value['role_id'], $position, $separate.' -- '));
		}
	}
	return $array;
}

function getSubDepartmentByRole($role_id = 0){
	if($role_id <= 0) $role_id = session('role_id');
	$department_id = M('Role')->where('role_id = %d', $role_id)->getField('department_id');
	//未完成方法
}
//通过部门id获取该部门员工  $sub=false为下属范围  $sub=true为部门所有人  
function getRoleByDepartmentId($department_id, $sub=false){
	$id_array = array($department_id);
	$departments = M('Department')->select();
	$where['role.department_id'] = $department_id;
	if(!$sub) $where['role.role_id'] = array('in', getSubRoleId());
	$roleList = D('RoleView')->where($where)->select();
	foreach($departments AS $value) {
		if ($department_id == $value['pid']) {
			$id_array[] = $value['department_id'];
			$role_list = getRoleByDepartmentId($value['department_id']);
			if(!empty($role_list)){
				$roleList = array_merge($roleList, $role_list);
			}
		}
	}
	return $roleList;
}



/**
 * Warning提示信息
 * @param string $type 提示类型 默认支持success, error, info
 * @param string $msg 提示信息
 * @param string $url 跳转的URL地址
 * @return void
 */
function alert($type='info', $msg='', $url='') {
    //多行URL地址支持
    $url        = str_replace(array("\n", "\r"), '', $url);
	$alert = unserialize(stripslashes(cookie('alert')));
    if (!empty($msg)) {
        $alert[$type][] = $msg;
		cookie('alert', serialize($alert));
	}
    if (!empty($url)) {
		if (!headers_sent()) {
			// redirect
			header('Location: ' . $url);
			exit();
		} else {
			$str    = "<meta http-equiv='Refresh' content='0;URL={$url}'>";
			exit($str);
		}
	}

	return $alert;
}

function parseAlert() {
	$alert = unserialize(stripslashes(cookie('alert')));
	cookie('alert', null);

	return $alert;
}


function getUserByRoleId($role_id,$field =""){
	if(empty($role_id)) return null;
	if($field == ""){
		$role = D('RoleView')->where('role.role_id = %d', $role_id)->find();
	}else{
		$role = D('RoleView')->where('role.role_id = %d', $role_id)->getField($field);	
	}
	return $role;
}

function getUserByRoleName($name){
	$role = D('RoleView')->where("(user.name like '".$name."%'  OR user.account like '".$name."%' )")->find();
	//dump(D('RoleView')->getLastSql());
	return $role;
}

function sendRequest($url, $params = array() , $headers = array()) {
	$ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
	if (!empty($params)) {
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
	}
	if (!empty($headers)) {
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
	}
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$txt = curl_exec($ch);
	if (curl_errno($ch)) {
        $array[0] = 0;
        $array[1] = L("CONNECT TO A SERVER ERROR");
        $array[2] = -1;
		$return = $array;
	} else {
		$return = json_decode($txt, true);
		if (!$return) {
            $array[0] = 0;
            $array[1] = L("THE SERVER RETURNS DATA ANOMALIES");
            $array[2] = -1;
			$return = $array;
		}
	}

	return $return;
}

//生成评论提醒标题
function createCommentAlertInfo($module,$module_id){
	$author = D('RoleView')->where('role.role_id = %d', session('role_id'))->find();
	if($module == 'log'){
		$log = M('log')->where('log_id = %d', $module_id)->find();
		$title = L('LOG COMMENT TITLE',array($log['subject'],$author['user_name'],$author['department_name'],$author['role_name']));
	}elseif($module == 'task'){
		$task = M('task')->where('task_id = %d', $module_id)->find();
        $title = L('TASK COMMENT TITLE',array($task['subject'],$author['user_name'],$author['department_name'],$author['role_name']));
	}
	return $title;
}

//$sysMessage=1 为系统消息
function sendMessage($id,$content,$sysMessage=0,$weixin = 0){
	if(!$id) return false;
	if(!$content) return false;
	$m_message = M('message');
	if($sysMessage == 0) $data['from_role_id'] = session('role_id');
	$data['to_role_id'] = $id;
	$data['content'] = $content;
	$data['read_time'] = 0;
	$data['send_time'] = time();
	return $m_message->add($data);
}

/*
	功能:发送邮件
	参数说明：  $to_role_id 收件人role_id
				$title 邮件主题
				$content 邮件内容
				$author 作者
*/
function sysSendEmail($to_role_id,$title,$content,$author){
	C(F('smtp'),'smtp');
	if(!$content) return false;
	if(!$to_role_id) return false;
	if(!$author) $author=C('defaultinfo.name').L('ADMIN');
	import('@.ORG.Mail');
	$to_user = D('RoleView')->where('role.role_id = %d', $to_role_id)->find();
	if(!is_email($to_user['email'])) return false;
	return SendMail($to_user['email'],$title,$content,$author);
}
function userSendEmail($address,$title,$content,$author=false){
	C(F('smtp'),'smtp');
	if(!$address) return false;
	if(!$content) return false;
	$content = preg_replace('/\\\\/','', $content);
	$userid = session('user_id');
    $user = M('user')->where(array('user_id'=>$userid))->find();
	if($author===true) $author=C('defaultinfo.name').'-'.$user['name'];
	else $author=C('defaultinfo.name');
	import('@.ORG.Mail');
	if(!is_email($address)) return false;
	return SendMail($address,$title,$content,$author);
}


function bsendemail($address,$title,$content,$file=array(),$author=false,$selfsmtp=false){
	if(!$address) return false;
	if(!$content) return false;
	$content = eregi_replace("[\]",'',$content);
	$userid = session('user_id');
	$user = M('user')->where(array('user_id'=>$userid))->find();
	if($author===true) $author=C('defaultinfo.name').'-'.$user['name'];
	else $author=C('defaultinfo.name')."-SmartCRM";

	if($selfsmtp){
		$smtp = M('UserSmtp')->where('smtp_id = %d', intval($selfsmtp))->find();
		C(unserialize($smtp['settinginfo']), 'smtp');
	}else{
		C(F('smtp'),'smtp');
	}
	
	import('@.ORG.Mail');
	$mail= new PHPMailer(true);
	try {
		$mail->IsSMTP();
		$mail->CharSet=C('MAIL_CHARSET');
		$mail->AddAddress($address);
		$mail->Body=$content;
		$mail->From= C('MAIL_ADDRESS');
		$mail->FromName=$author;
		$mail->Subject=$title;
		$mail->Host=C('MAIL_SMTP');
		$mail->SMTPAuth=C('MAIL_AUTH');
		$mail->Username=C('MAIL_LOGINNAME');
		$mail->Password=C('MAIL_PASSWORD');  
		$mail->IsHTML(C('MAIL_HTML'));
		$mail->MsgHTML($content);
		 ////对邮件正文进行重新编码，保证中文内容不乱码 如果正文引用该图片 就不会以附件形式存在 而是在正文中
		if(!empty($file)){
			foreach($file as $k=>$v){
				$mail->AddAttachment(ltrim($v,'/'));
			}
		}

		//$mail->AddAttachment($content); //上传附件内容
		return($mail->Send());
	} catch (phpmailerException $e) {
	 // echo $e->errorMessage(); //Pretty error messages from PHPMailer
	} catch (Exception $e) {
	  //echo $e->getMessage(); //Boring error messages from anything else!
	}
}

function sysSendSms($to_role_id,$content){

	if(!$content) return false;
	if(!$to_role_id) return false;
	if(!$title) $title="系统通知";
	if(!$author) $author=C('defaultinfo.name').L('ADMIN');

	$to_user = D('RoleView')->where('role.role_id = %d', $to_role_id)->find();
	if(!is_email($to_user['email'])) return 100;
	return sendSMS($to_user['telephone'],$content,'sign_sysname');
}

function isMobile(){

    $user_agent = $_SERVER['HTTP_USER_AGENT'];

    $mobile_agents = Array("240x320","acer","acoon","acs-","abacho","ahong","airness","alcatel","amoi","android","anywhereyougo.com","applewebkit/525","applewebkit/532","asus","audio","au-mic","avantogo","becker","benq","bilbo","bird","blackberry","blazer","bleu","cdm-","compal","coolpad","danger","dbtel","dopod","elaine","eric","etouch","fly ","fly_","fly-","go.web","goodaccess","gradiente","grundig","haier","hedy","hitachi","htc","huawei","hutchison","inno","ipad","ipaq","ipod","jbrowser","kddi","kgt","kwc","lenovo","lg ","lg2","lg3","lg4","lg5","lg7","lg8","lg9","lg-","lge-","lge9","longcos","maemo","mercator","meridian","micromax","midp","mini","mitsu","mmm","mmp","mobi","mot-","moto","nec-","netfront","newgen","nexian","nf-browser","nintendo","nitro","nokia","nook","novarra","obigo","palm","panasonic","pantech","philips","phone","pg-","playstation","pocket","pt-","qc-","qtek","rover","sagem","sama","samu","sanyo","samsung","sch-","scooter","sec-","sendo","sgh-","sharp","siemens","sie-","softbank","sony","spice","sprint","spv","symbian","tablet","talkabout","tcl-","teleca","telit","tianyu","tim-","toshiba","tsm","up.browser","utec","utstar","verykool","virgin","vk-","voda","voxtel","vx","wap","wellco","wig browser","wii","windows ce","wireless","xda","xde","zte");

    $is_mobile = false;

    foreach ($mobile_agents as $device) {
        if (stristr($user_agent, $device)) {
            $is_mobile = true;
            break;
        }
    }

    return $is_mobile;
}

function is_utf8($liehuo_net){
	if (preg_match("/^([".chr(228)."-".chr(233)."]{1}[".chr(128)."-".chr(191)."]{1}[".chr(128)."-".chr(191)."]{1}){1}/",$liehuo_net) == true || preg_match("/([".chr(228)."-".chr(233)."]{1}[".chr(128)."-".chr(191)."]{1}[".chr(128)."-".chr(191)."]{1}){1}$/",$liehuo_net) == true || preg_match("/([".chr(228)."-".chr(233)."]{1}[".chr(128)."-".chr(191)."]{1}[".chr(128)."-".chr(191)."]{1}){2,}/",$liehuo_net) == true) 
	{
		return true; 
	}
	else 
	{ 
		return false; 
	}
}

//验重二维数组排序  $arr 数组 $keys比较的键值
function array_sort($arr,$keys,$type='asc'){ 
	$keysvalue = $new_array = array();
	foreach ($arr as $k=>$v){
		$keysvalue[$k] = $v[$keys];
	}
	if($type == 'asc'){
		asort($keysvalue);
	}else{
		arsort($keysvalue);
	}
	reset($keysvalue);
	$i = 0;
	foreach ($keysvalue as $k=>$v){
		if($i < 8 && $arr[$k][search] > 0){
			$new_array[] = $arr[$k]['value'];
			$i++;
		}
		
	}
	return $new_array; 
}

/**
 * function	对二位数组进行指定规则的排序
 * return	排序后的二维数组
 * @arr 	传入要排序的数组
 * @keys	要排序的字段
 * @type	排序规则
 **/
function array_sorts($arr,$keys,$type='asc'){
	$keysvalue = $new_array = array();
	foreach ($arr as $k=>$v){
		$keysvalue[$k] = $v[$keys];
	}
	if($type == 'asc'){
		asort($keysvalue);
	}else{
		arsort($keysvalue);
	}
	reset($keysvalue);
	foreach ($keysvalue as $k=>$v){
		$new_array[$k] = $arr[$k];
	}
	return $new_array; 
}

//自定义字段html输出     $field为特殊验证字段   $d_module=($ModuleView) 
function field_list_html($type="add",$module="",$d_module=array()){
	if ($type == "add" || $type == 'edit') {
		$model = get_module_id(strtolower($module));
		$field_list1 = M('Fields')->where('model = "'.$model.'" and in_add = 1')->order('order_id')->select();
	} else {
		$field_list1 = M('Fields')->where('model = "'.$model.'"')->order('order_id')->select();
	}
    foreach ($field_list1 as $key => $value1) {
    	$value1['name'] = L($value1['name']);
    	$field_list[]=$value1;
    }
	foreach($field_list as $k=>$v){
		if(trim($v['input_tips'])){
			$input_tips = ' &nbsp; <span style="color:#005580;">('.L('NOTE_').$v['input_tips'].')</span>';
		}else{
			$input_tips = '';
		}
		if('add' == $type){
			$value = $v['default_value'];
		} elseif ('edit' == $type && !empty($d_module)) {
			//dump($d_module['status']);exit;
			$value = $d_module[$v['field']] !== '' ? $d_module[$v['field']] : '';
		}
		if($v['is_validate'] == "1" AND $v['is_null'] == "1"){
			$required =" required='' ";
		}else{
			$required ='';
		}
		//dump($v);
		switch ($v['form_type']) {
			case 'textarea' :
				$field_list[$k]['html'] = '<textarea '.$required.' rows="2" class="form-control" id="'.$v['field'].'" name="'.$v['field'].'" >'.$value.'</textarea>'.$input_tips;
				break;
			case 'box' :
			/** wangchao  2016-04-16 **/
				$option_type = M('field_option')->where('field_id='.$v['field_id'])->field('field_type')->find();
				$option_values1 = M('field_option_value')->where('field_id='.$v['field_id'])->field('id,field_value,is_default_value')->order('order_id')->select();
				$option_values=array();
				foreach ($option_values1 as $kov => $vov) {
					$vov['field_value']=L($vov['field_value']);
					$option_values[] = $vov;
				}
				//out($option_type,$option_values);
				if($option_type['field_type'] == 1){	//raido 单选 
					$str = '';
					$i = '';
					$str .= "<div class='row'>";
					foreach ($option_values as $v1) {
					
						if ('add' == $type) {
							$str .= "<div class='radio i-checks'>&nbsp;<label>&nbsp;&nbsp;<input type='radio' name='".$v['field']."' id='".$v['field'].$i."' value=".$v1['id'];
							$str .= $v1['is_default_value'] == 1 ? ' checked="checked"':'';
							$str .= ' /><i></i>&nbsp;&nbsp;' .$v1['field_value'].'</label></div>';
                                   
						}else if ('edit' == $type) {
							$str .= "<div class='radio i-checks'>&nbsp;<label>&nbsp;&nbsp;<input type='radio' 
							name ='".$v['field']."' 
							id   ='".$v['field'].$i."' 
							value=".$v1['id'];
							$str .= $v1['id'] ==  $d_module[$v['field']] ? ' checked="checked"':'';
							$str .= '/><i></i>&nbsp;&nbsp;' .$v1['field_value'].'</label></div>';
							
						}
							
							$i++;
					}
					$str .= "</div>";
					$field_list[$k]['html'] = $str.$input_tips;
					break;
				}else if($option_type['field_type'] == 2){	// checkbox 多选
					$str = '';
					$i = '';
					foreach ($option_values as $v2) {		
							$str .= " &nbsp; <input type='checkbox' name='".$v['field']."[]' id='".$v['field'].$i."' value=".$v2['id'];
							$str .= $v2['is_default_value'] == 1  ? ' checked="checked" ':'';
							$str .= '/>&nbsp;' .$v2['field_value'];
							$i++;
					}
					$field_list[$k]['html'] = $str.$input_tips;
					break;
				}else if($option_type['field_type'] == 3){	//select 下拉

					//如果是部门，直接获取部门列表 zhangtuo 2016-4-30
					if($v['field'] == "d_id"){
						$field_list[$k]['html'] = getSubDepartmentHtml($v['field'],$v['field']);
					}elseif($v['field'] == "sea_id"){
						$field_list[$k]['html'] = getSeaListHtml($module,$v['field'],$v['field']);				
					}else{
						$str = '';
						$str .= "<option value=''>--".L('PLEASE_CHOOSE')."--</option>";
						foreach ($option_values as $v3) {		
								$str .= "<option value=".$v3['id'];
								if ('edit' == $type) {
									$str .= $v3['id'] ==  $value ? ' selected="selected"':'';
								}elseif ('add' == $type) {
									$str .= $v3['is_default_value'] == 1  ? ' selected="selected" ':'';
								}
								
								$str .= ">&nbsp;".$v3['field_value']."</option>";
						}
						$field_list[$k]['html'] = '<select  '.$required.' id="'.$v['field'].'" name="'.$v['field'].'"  class="form-control">'.$str.'</select>'.$input_tips;
						break;
					}
				}
				break;
			case 'editor' :
				$upload_url = U('file/editor');
				$fileManagerJson = U('file/manager');
				$field_list[$k]['html'] = '<script type="text/javascript">
				var editor;
				KindEditor.ready(function(K) {
					editor = K.create(\'textarea[name="'.$v['field'].'"]\', {
						uploadJson:"'.$upload_url.'",
						allowFileManager : true,
						loadStyleMode : false,
						fileManagerJson: "'.$fileManagerJson.'"
					});
				});
				</script>
				<textarea name="'.$v['field'].'" id="'.$v['field'].'"  '.$required.'  class="form-control">'.$value.'</textarea>'.$input_tips;
				break;
			case 'datetime' :
				if($v['field'] == 'nextstep_time'){
					$time_accuracy = 'yyyy-MM-dd HH:mm';
				}else{
					$time_accuracy = 'yyyy-MM-dd';
				}
				$field_list[$k]['html'] = '<input  onFocus="WdatePicker({dateFmt:\''.$time_accuracy.'\'})" name="'.$v['field'].'" id="'.$v['field'].'"  class="form-control" type="text" value="'.pregtime($value).'"/>'.$input_tips;
				break;
			case 'number' :
				//如果是部门
				//dump($v['field']);
				if($v['field'] == "d_id"){
					//zte
					$field_list[$k]['html'] = getSubDepartmentHtml($v['field'],$v['field']);
					
				}elseif($v['field'] == "sea_id"){
					$field_list[$k]['html'] = getSeaListHtml($module,$v['field'],$v['field']);				
				}else{
					$field_list[$k]['html'] = '<input type="text"  class="form-control" data-type="nummber"   '.$required.' id="'.$v['field'].'" name="'.$v['field'].'" maxlength="'.$v['max_length'].'" value="'.$value.'"/> '.$input_tips;
				}
				break;
			case 'unionnumber' :
				//如果是部门
				//dump($v['field']);
				if($v['field'] == "d_id"){
					//zte
					$field_list[$k]['html'] = getSubDepartmentHtml($v['field'],$v['field']);
					
				}elseif($v['field'] == "sea_id"){
					$field_list[$k]['html'] = getSeaListHtml($module,$v['field'],$v['field']);				
				}else{
					$field_list[$k]['html'] = '<input type="text"  class="form-control" data-type="nummber"   '.$required.' id="'.$v['field'].'" name="'.$v['field'].'" maxlength="'.$v['max_length'].'" value="'.$value.'"/> '.$input_tips;
				}
				break;	
			case 'floatnumber' :
				$value = $value > 0 ? $value : ''; 
				$field_list[$k]['html'] = '<input type="text"  class="form-control" '.$required.' id="'.$v['field'].'" name="'.$v['field'].'" value="'.$value.'"/>'.$input_tips;
				break;
			case 'address':
				if('add' == $type){
					$defaultinfo = unserialize(M('Config')->where('name = "defaultinfo"')->getField('value'));
					$state = $defaultinfo['state'];
					$city = $defaultinfo['city'];
					$area = $defaultinfo['area'];
				}else{
					$address_array = explode(chr(10),$value);
					$state = $address_array[0];
					$city = $address_array[1];
					$area = $address_array[2];
					$street = $address_array[3];
				}
				$field_list[$k]['html'] = '<script type="text/javascript">
				$(function(){
					new PCAS("'.$v['field'].'[\'state\']","'.$v['field'].'[\'city\']","'.$v['field'].'[\'area\']","'.$state.'","'.$city.'","'.$area.'");
				});
				</script><select name="'.$v['field'].'[\'state\']" class="form-control"></select> 
					<select name="'.$v['field'].'[\'city\']" class="form-control"></select>
					<select name="'.$v['field'].'[\'area\']" class="form-control"></select>
					<input type="text" name="'.$v['field'].'[\'street\']" placeholder="'.L('THE STREET INFORMATION').'" class="form-control" value="'.$street.'">';
				break;
			case 'p_box':
					$str = '';
					$category = M('product_category');
					$category_list = $category->select();
					$categoryList = getSubCategory(0, $category_list, '');
					foreach ($categoryList as $v2) {
						$checked = '';
						if($v2['category_id'] == $value){
							$checked = 'selected="selected"';
						}
						$str .= "<option $checked value=".$v2['category_id'].">".$v2['name']."</option>";
						
					}
					$field_list[$k]['html'] = '<select id="'.$v['field'].'" name="'.$v['field'].'"  '.$required.' class="form-control">'.$str.'</select>'.$input_tips;

				break;
			case 'b_box':
					$status = M('BusinessStatus')->order('order_id')->select();
					$str = '';
					foreach ($status as $v2) {
						$checked = '';
						if($v2['status_id'] == $value){
							$checked = 'selected="selected"';
						}
						$str .= "<option $checked value='".$v2['status_id']."'>".$v2['name']."</option>";
					}
					$field_list[$k]['html'] = '<select id="'.$v['field'].'" name="'.$v['field'].'"  '.$required.' class="form-control">'.$str.'</select>'.$input_tips;
				break;
			case 'email':
				$field_list[$k]['html'] = '<input class="form-control" '.$required.' type="email" id="'.$v['field'].'" name="'.$v['field'].'" maxlength="'.$v['max_length'].'" value="'.$value.'"/>'.$input_tips;
				break;
			default: 
				if ($v['field'] == 'create_time' || $v['field'] == 'update_time') {
					break;
				}else{
					$customer_id = intval($_GET['customer_id']);
					if($v['field'] == 'name' && $customer_id && $module == 'customer') $value=M('customer')->where('customer_id = %d', $customer_id)->getField('name');
					$field_list[$k]['html'] = '<input class="form-control" '.$required.' type="text" id="'.$v['field'].'" name="'.$v['field'].'" maxlength="'.$v['max_length'].'" value="'.$value.'"/>'.$input_tips;
					//dump($required);
				}
				break;
		}
        //if($field_list[$k]['is_main'] == 1){
        //    $fieldlist['main'][] = $field_list[$k];
        //}else{
        //    $fieldlist['data'][] = $field_list[$k];
        //}
		$fieldlist[] = $field_list[$k];
	}
	return $fieldlist;
}
/**
 * function	根据customer_id获取客户姓名
 * return	队列数组
 * @type	查询类
 * @autor   dongjun
 **/
function getCustomerNameById($id)
{
  $name = M("Customer")->where('customer_id=%d',$id)->getField('name',true);
  return $name[0];
}
/**
 * function	获取asterisk中的所有队列
 * return	队列数组
 * @type	查询类
 * @autor   dongjun
 **/
function getQueuesList()
{
   $cti_db_name = C('CTI_DB');
   $m   = new Model(); //定义一个空的model
   $arr = $m->query("select extension as queue_id,descr as queue_note from `$cti_db_name`.`queues_config`  order by extension asc");
   //$arr1 = $m->query("select extension as queue_id,descr as queue_note from `cti`.`queues_config` where extension in ( $extensions ) order by extension asc");
   return $arr;
}
/**
 * function	获取r_queue_exten中的分机队列
 * return	队列数组
 * @type	查询类
 * @autor   dongjun
 **/
function getRQueueExten($queue_id)
{
	if(!$queue_id)
	{
	  return false;	
	}
	$extens_ids = M('rQueueExten')->where("queue_id=%s",$queue_id)->getField('exten', true);
	$extens_ids = is_null($extens_ids) ? array() : $extens_ids;
	return $extens_ids;
}
/**
 * function	获取API中的某个队列的分机
 * return	队列数组
 * @type	获取类
 * @autor   dongjun
 **/
function getApiQueueExten($queue_id)
{
	if(!$queue_id)
	{
	  return false;	
	}
	$r = A('Api')->getQueueExten($queue_id);
	if (!$r['error']) {
		$exten_ids = $r['msg'];
	} else {
		$exten_ids = array();
	}
	return $exten_ids;
}
/**
 * function	新增分机队列关系到r_queue_exten
 * return	int - 及成功添加多少条
 * @type	操作类
 * @autor   dongjun
 **/
function addRQueueExten($extens,$queue_id)
{
	if(!$extens || !$queue_id)
	{
	  return false;	
	}
	$m     = M('rQueueExten');
	$table = $m->getTableName();
	foreach($extens as $exten)
	{
	  $r = $m->execute("INSERT INTO $table (queue_id,exten) VALUES($queue_id,$exten)");	
	  if($r)
	  {
		$success ++;  
	  }
	}
	return $success;
}
/**
 * function	删除r_queue_exten中对应队列的分机
 * return	int - 及成功删除多少条
 * @type	操作类
 * @autor   dongjun
 **/
function delRQueueExten($extens,$queue_id)
{
	if(!$extens || !$queue_id)
	{
	  return false;	
	}
	$m     = M('rQueueExten');	
	$table = $m->getTableName();
	$extens_ids = implode(",",$extens);
	$r     = $m->execute("DELETE FROM $table WHERE queue_id = $queue_id AND exten in($extens_ids)");
	return $r;
}
/**
 * function	检查队列分机是否跟asterisk中同步
 * return	处理状态
 * @type	入口类
 * @autor   dongjun
 **/
function checkAllQueueExtens()
{
	 $result   = array('status'=>'success','tip'=>L('SUCCESS_U'));
	 //获取所有队列
	 $queue_list = getQueuesList();
	 array_walk($queue_list,"handleQueueExtenAtWalk");
	 return $result;
}
/**
 * function	检查某个队列r_queue_exten分机和asterisk中是否同步
 * return	队列数组
 * @type	控制类
 * @autor   dongjun
 **/
function handleQueueExtenAtWalk($queue_arr,$k)
{
	if(!is_array($queue_arr))
	{
	  return false;	
	}
	$queue_id = $queue_arr['queue_id'];
	//获得r_queue_exten分机数组
	$rQExtens   = getRQueueExten($queue_id);
	//获得API那边的分机数组
	$apiQExtens = getApiQueueExten($queue_id);
	//如果其中一个获取不成功
	if(!is_array($apiQExtens) || !is_array($rQExtens))
	{
		return false;
	}
	//存在于api的，但是不存在与r_queue_exten的，需要增加
	$extenAdd = array_diff($apiQExtens,$rQExtens);
	addRQueueExten($extenAdd,$queue_id);
	//存在于r_queue_exten中，但是不在于api的，需要删除
	$extenDel = array_diff($rQExtens,$apiQExtens);
    delRQueueExten($extenDel,$queue_id);
}
/**
 * function	根据recordingfile获取unique
 * return	队列数组
 * @type	控制类
 * @autor   dongjun
 **/
function getUniqueidByRfile($filename)
{
	if(!$filename)
	{
	   return '';	
	}
	$temp = array();
	$temp = explode('-',$filename);
	$uniqueid = str_replace(".mp3","",$temp[4]);
	$uniqueid = str_replace(".","",$uniqueid);
	return $uniqueid;
}
/**
 * function	根据customer_id来确定是否可以被当前用户管理
 * return	bool
 * @date    2016-12-05
 * @autor   dongjun
 **/
function checkCusomterSeaUser($customer_id)
{
  $result = false;
  if(!!$customer_id)
  {
	  $m = M();
	  $prefix = C('DB_PREFIX');
	  $customerInfo = $m->query("SELECT c.customer_id,c.customer_status,c.sea_id,s.default_owner_user_id FROM ".$prefix."customer as c LEFT JOIN ".$prefix."sea as s ON c.sea_id = s.sea_id WHERE c.customer_id = ".$customer_id);	
	  $customerInfo = $customerInfo[0];
	  if($customerInfo['customer_status'] == 310)
	  {
		$result = true;
	  }else{
		$result = $customerInfo['default_owner_user_id'] == NULL ? true : $customerInfo['default_owner_user_id'] == session('user_id');
	  }
  }
  return $result;
}

// function message_field_list_html($type="add",$module="",$d_module=array()){
// 	if ($type == "add" || $type == 'edit') {
// 		$model = get_module_id(strtolower($module));
// 		$field_list = M('Fields')->where('model = "'.$model.'"')->order('order_id')->select();
// 	} else {
// 		$field_list = M('Fields')->where('model = "'.$model.'"')->order('order_id')->select();
// 	}
// 	foreach($field_list as $k=>$v){
// 		if(trim($v['input_tips'])){
// 			$input_tips = ' &nbsp; <span style="color:#005580;">('.L('NOTE_').$v['input_tips'].')</span>';
// 		}else{
// 			$input_tips = '';
// 		}
// 		if('add' == $type){
// 			$value = $v['default_value'];
// 		} elseif ('edit' == $type && !empty($d_module)) {
// 			$value = $d_module[$v['field']] !== '' ? $d_module[$v['field']] : '';
// 		}
// 		if($v['is_validate'] == "1" AND $v['is_null'] == "1"){
// 			$required =" required='' ";
// 		}else{
// 			$required = '';
// 		}
// 		//dump($v);
// 		switch ($v['form_type']) {
// 			case 'textarea' :
// 				$field_list[$k]['html'] = '<label style="padding-top:6px">'.$value.'</label>';
// 				break;
// 			case 'box' :

// 			/** wangchao  2016-04-16 **/
			
// 				$option_type = M('field_option')->where('field_id='.$v['field_id'])->field('field_type')->find();
// 				$option_values = M('field_option_value')->where('field_id='.$v['field_id'])->field('id,field_value,is_default_value')->order('order_id')->select();

// 				if($option_type['field_type'] == 1){	//raido 单选 
// 					$str = '';
// 					$i = '';
// 					foreach ($option_values as $v1) {		
// 							$str .= " &nbsp;<label><input type='radio' name='".$v['field']."' id='".$v['field'].$i."' value=".$v1['id'];
// 							$str .= $v1['is_default_value'] == 1 ? ' checked="checked"':'';
// 							$str .= '/>&nbsp;' .$v1['field_value'].'</label>';
// 							//$str .=" <div class='radio radio-info radio-inline'><input type='radio' id='".$v['field'].$i."' value='".$v1."' name='".$v['field']."' ";
// 							//$str .= $d_module[$v['field']] == $v1 ? ' checked='checked'':'';
// 							//$str .= "><label for='".$v['field'].$i."'> ".$v1." </label>";

// 							$i++;
// 					}
// 					$field_list[$k]['html'] = $str.$input_tips;
// 					break;
// 				}else if($option_type['field_type'] == 2){	// checkbox 多选
// 					$str = '';
// 					$i = '';
// 					foreach ($option_values as $v2) {		
// 							$str .= " &nbsp; <input type='checkbox' name='".$v['field']."[]' id='".$v['field'].$i."' value=".$v2['id'];
// 							$str .= $v2['is_default_value'] == 1  ? ' checked="checked" ':'';
// 							$str .= '/>&nbsp;' .$v2['field_value'];
// 							$i++;
// 					}
// 					$field_list[$k]['html'] = $str.$input_tips;
// 					break;
// 				}else if($option_type['field_type'] == 3){	//select 下拉

// 					//如果是部门，直接获取部门列表 zhangtuo 2016-4-30
// 					if($v['field'] == "d_id"){
// 						$field_list[$k]['html'] = getSubDepartmentHtml($v['field'],$v['field']);
// 					}elseif($v['field'] == "sea_id"){
// 						$field_list[$k]['html'] = getSeaListHtml($module,$v['field'],$v['field']);				
// 					}else{
// 						$str = '';
// 						$str .= "<option value=''>--".L('PLEASE CHOOSE')."--</option>";
// 						foreach ($option_values as $v3) {		
// 								$str .= "<option value=".$v3['id'];
// 								$str .= $v3['is_default_value'] == 1  ? ' selected="selected" ':'';
// 								$str .= ">&nbsp;".$v3['field_value']."</option>";
// 						}
// 						switch ($value) {
// 							case '1':
// 								$value = '已读';
// 								break;
// 							case '0':
// 								$value = '未读';
// 								break;
// 						}
// 						$field_list[$k]['html'] = '<label  style="padding-top:6px">'.$value.'</label>';

// 						break;
// 					}
// 				}
// 				break;
// 			case 'editor' :
// 				$upload_url = U('file/editor');
// 				$fileManagerJson = U('file/manager');
// 				$field_list[$k]['html'] = '<script type="text/javascript">
// 				var editor;
// 				KindEditor.ready(function(K) {
// 					editor = K.create(\'textarea[name="'.$v['field'].'"]\', {
// 						uploadJson:"'.$upload_url.'",
// 						allowFileManager : true,
// 						loadStyleMode : false,
// 						fileManagerJson: "'.$fileManagerJson.'"
// 					});
// 				});
// 				</script>
// 				<textarea name="'.$v['field'].'" id="'.$v['field'].'"  '.$required.'  class="form-control">'.$value.'</textarea>'.$input_tips;
// 				break;
// 			case 'datetime' :
// 				if($v['field'] == 'nextstep_time'){
// 					$time_accuracy = 'yyyy-MM-dd HH:mm';
// 				}else{
// 					$time_accuracy = 'yyyy-MM-dd';
// 				}
// 				$field_list[$k]['html'] = '<label style="padding-top:6px">'.getDiffTime($value).'</label>';
// 				break;
// 			case 'number' :
// 				//如果是部门
// 				//dump($v['field']);
// 				if($v['field'] == "d_id"){
// 					//zte
// 					$field_list[$k]['html'] = getSubDepartmentHtml($v['field'],$v['field']);
					
// 				}elseif($v['field'] == "sea_id"){
// 					$field_list[$k]['html'] = getSeaListHtml($module,$v['field'],$v['field']);				
// 				}else{
// 					$field_list[$k]['html'] = '<input type="text"  class="form-control" data-type="nummber"   '.$required.' id="'.$v['field'].'" name="'.$v['field'].'" maxlength="'.$v['max_length'].'" value="'.$value.'"/> '.$input_tips;
// 				}
// 				break;
// 			case 'floatnumber' :
// 				$value = $value > 0 ? $value : ''; 
// 				$field_list[$k]['html'] = '<input type="text"  class="form-control" '.$required.' id="'.$v['field'].'" name="'.$v['field'].'" value="'.$value.'"/>'.$input_tips;
// 				break;
// 			case 'address':
// 				if('add' == $type){
// 					$defaultinfo = unserialize(M('Config')->where('name = "defaultinfo"')->getField('value'));
// 					$state = $defaultinfo['state'];
// 					$city = $defaultinfo['city'];
// 					$area = $defaultinfo['area'];
// 				}else{
// 					$address_array = explode(chr(10),$value);
// 					$state = $address_array[0];
// 					$city = $address_array[1];
// 					$area = $address_array[2];
// 					$street = $address_array[3];
// 				}
// 				$field_list[$k]['html'] = '<script type="text/javascript">
// 				$(function(){
// 					new PCAS("'.$v['field'].'[\'state\']","'.$v['field'].'[\'city\']","'.$v['field'].'[\'area\']","'.$state.'","'.$city.'","'.$area.'");
// 				});
// 				</script><select name="'.$v['field'].'[\'state\']" class="form-control"></select> 
// 					<select name="'.$v['field'].'[\'city\']" class="form-control"></select>
// 					<select name="'.$v['field'].'[\'area\']" class="form-control"></select>
// 					<input type="text" name="'.$v['field'].'[\'street\']" placeholder="'.L('THE STREET INFORMATION').'" class="form-control" value="'.$street.'">';
// 				break;
// 			case 'p_box':
// 					$str = '';
// 					$category = M('product_category');
// 					$category_list = $category->select();
// 					$categoryList = getSubCategory(0, $category_list, '');
// 					foreach ($categoryList as $v2) {
// 						$checked = '';
// 						if($v2['category_id'] == $value){
// 							$checked = 'selected="selected"';
// 						}
// 						$str .= "<option $checked value=".$v2['category_id'].">".$v2['name']."</option>";
						
// 					}
// 					$field_list[$k]['html'] = '<select id="'.$v['field'].'" name="'.$v['field'].'"  '.$required.' class="form-control">'.$str.'</select>'.$input_tips;

// 				break;
// 			case 'b_box':
// 					$status = M('BusinessStatus')->order('order_id')->select();
// 					$str = '';
// 					foreach ($status as $v2) {
// 						$checked = '';
// 						if($v2['status_id'] == $value){
// 							$checked = 'selected="selected"';
// 						}
// 						$str .= "<option $checked value='".$v2['status_id']."'>".$v2['name']."</option>";
// 					}
// 					$field_list[$k]['html'] = '<select id="'.$v['field'].'" name="'.$v['field'].'"  '.$required.' class="form-control">'.$str.'</select>'.$input_tips;
// 				break;
// 			case 'email':
// 				$field_list[$k]['html'] = '<input class="form-control" '.$required.' type="email" id="'.$v['field'].'" name="'.$v['field'].'" maxlength="'.$v['max_length'].'" value="'.$value.'"/>'.$input_tips;
// 				break;
// 			default: 
// 				if ($v['field'] == 'create_time' || $v['field'] == 'update_time') {
// 					break;
// 				}else{
// 					$customer_id = intval($_GET['customer_id']);
// 					if($v['field'] == 'name' && $customer_id && $module == 'customer') $value=M('customer')->where('customer_id = %d', $customer_id)->getField('name');
// 					$field_list[$k]['html'] = '<label style="padding-top:6px">'.$value.'</label>';
// 					//dump($required);
// 				}
// 				break;
// 		}
//         //if($field_list[$k]['is_main'] == 1){
//         //    $fieldlist['main'][] = $field_list[$k];
//         //}else{
//         //    $fieldlist['data'][] = $field_list[$k];
//         //}
// 		$fieldlist[] = $field_list[$k];
// 	}
// 	return $fieldlist;
// }
//自定义字段html输出     $field为特殊验证字段   $d_module=($ModuelView) 
function field_list_html_old($type="add",$module="",$d_module=array()){
	if ($type == "add") {
		$field_list = M('Fields')->where('model = "'.$module.'" and in_add = 1')->order('order_id')->select();
	} else {
		$field_list = M('Fields')->where('model = "'.$module.'"')->order('order_id')->select();
	}
	
	foreach($field_list as $k=>$v){
		if(trim($v['input_tips'])){
			$input_tips = ' &nbsp; <span style="color:#005580;">('.L('NOTE_').$v['input_tips'].')</span>';
		}else{
			$input_tips = '';
		}
		if('add' == $type){
			$value = $v['default_value'];
		} elseif ('edit' == $type && !empty($d_module)) {
			$value = $d_module[$v['field']] !== '' ? $d_module[$v['field']] : '';
		}
		
		if($d_module['customer_id']){
			$customer_id = intval($d_module['customer_id']);
		}else{
			$customer_id = intval($_GET['customer_id']);
		}
		
		if($customer_id){
			$customer = M('customer')->where('customer_id = %d', $customer_id)->find();
			if($d_module['contacts_id']){
				$contacts = M('contacts')->where('contacts_id = %d', $d_module['contacts_id'])->find();
			}else{
				$contacts = M('contacts')->where('contacts_id = %d', $customer['contacts_id'])->find();
			}
		}
		if ($v['field'] == 'customer_id') {
			if($customer_id){	
				$field_list[$k]['html'] = '<input type="hidden" name="'.$v['field'].'" id="customer_id" value="'.$customer['customer_id'].'"/><input  type="text" name="customer_name" id="customer_name" value="'.$customer['name'].'"/> <a target="_blank" href="'.U('customer/add').'">'.L('CREATE NEW CUSTOMER').'</a>';
			}else{
				$field_list[$k]['html'] = '<input type="hidden" name="'.$v['field'].'" id="customer_id"/><input  type="text" name="customer_name" id="customer_name"> <a target="_blank" href="'.U('customer/add').'">'.L('CREATE NEW CUSTOMER').'</a>';
			}
		}elseif($v['field'] == 'contacts_id'){
			if($customer_id){
				$field_list[$k]['html'] = '<input type="hidden" name="contacts_id" id="contacts_id" value="'.$contacts['contacts_id'].'"/><input  type="text" name="contacts_name" id="contacts_name" value="'.$contacts['name'].'"/>';
			}else{
				$field_list[$k]['html'] = '<input type="hidden" name="contacts_id" id="contacts_id"/><input  type="text" name="contacts_name" id="contacts_name"/>';
			}
		}elseif($module == 'customer' && $v['field'] == 'tags'){
			//客户标签
			$tagsStr = substr($d_module['tags'], '1', strlen($d_module['tags'])-2);
			if($tagsStr !=''){
				$tagsName = M('tags')->where('tags_id in ( %s )', $tagsStr)->getField('name',true);
			}
			$field_list[$k]['html'] = '<input type="text" name="tags" id="tags" value="'.implode(',', $tagsName).'" />';
		}else{
            switch ($v['form_type']) {
                case 'textarea' :
                    $field_list[$k]['html'] = '<textarea  rows="6"  class="form-control" id="'.$v['field'].'" name="'.$v['field'].'" >'.$value.'</textarea> &nbsp;  <span id="'.$v['field'].'Tip" style="color:red;"></span>'.$input_tips;
                    break;
                case 'box' :
                    $setting_str = '$setting='.$v['setting'].';';
                    eval($setting_str);

                    $field_list[$k]['setting'] = $setting;
                    if ($setting['type'] == 'select') {
                        $str = '';
                        $str .= "<option value=''>--".L('PLEASE CHOOSE')."--</option>";
                        foreach ($setting['data'] as $v2) {
                            $str .= "<option value='$v2'";
                            $str .= $d_module[$v['field']] == $v2 ? ' selected="selected" ':'';
                            $str .= ">$v2</option>";
                        }
                        $field_list[$k]['html'] = '<select id="'.$v['field'].'" name="'.$v['field'].'">'.$str.'</select> &nbsp;  <span id="'.$v['field'].'Tip" style="color:red;"></span>'.$input_tips;
						break;
                    } elseif ($setting['type'] == 'radio') {
                        $str = '';
                                $i = '';
                        foreach ($setting['data'] as $v2) {
                            $str .= " &nbsp; <input type='radio' name='".$v['field']."' id='".$v['field'].$i."' value='$v2'";
                            $str .= $d_module[$v['field']] == $v2 ? ' checked="checked"':'';
                            $str .= "/>&nbsp; $v2";
                            $i++;
                        }
                        $field_list[$k]['html'] = $str.'  <span id="'.$v['field'].'Tip" style="color:red;"></span>&nbsp; '.$input_tips;
                        break;
                    } elseif ($setting['type'] == 'checkbox') {
                        $str = '';
                        $i = '';
                        foreach ($setting['data'] as $v2) {
                            $str .= " &nbsp; <input type='checkbox' name='".$v['field']."[]' id='".$v['field'].$i."' value='$v2'";
                            if(strstr($d_module[$v['field']],$v2)){
                                $str .= ' checked="checked"';
                            }
                            $str .= '/>&nbsp;' .$v2;
                            $i++;
                        }
                        $field_list[$k]['html'] = $str.' <span id="'.$v['field'].'Tip" style="color:red;"></span>&nbsp; '.$input_tips;
                        break;
                    }
                    break;
                case 'editor' :
                    $upload_url = U('file/editor');
					$fileManagerJson = U('file/manager');
                    $field_list[$k]['html'] = '<script type="text/javascript">
                    var editor;
                    KindEditor.ready(function(K) {
                        editor = K.create(\'textarea[name="'.$v['field'].'"]\', {
                            uploadJson:"'.$upload_url.'",
                            allowFileManager : true,
                            loadStyleMode : false,
							fileManagerJson: "'.$fileManagerJson.'"
                        });
                    });
                    </script>
                    <textarea name="'.$v['field'].'" id="'.$v['field'].'" style="width: 800px; height: 350px;">'.$value.'</textarea> &nbsp;  <span id="'.$v['field'].'Tip" style="color:red;"></span>'.$input_tips;
                    break;
                case 'datetime' :
					if($v['field'] == 'nextstep_time'){
						$time_accuracy = 'yyyy-MM-dd HH:mm';
					}else{
						$time_accuracy = 'yyyy-MM-dd';
					}
                    $field_list[$k]['html'] = '<input  onFocus="WdatePicker({dateFmt:\''.$time_accuracy.'\'})" name="'.$v['field'].'" id="'.$v['field'].'" type="text"  class="form-control" value="'.pregtime($value).'"/> &nbsp;  <span id="'.$v['field'].'Tip" style="color:red;"></span>'.$input_tips;
                    break;
                case 'number' :
                    $field_list[$k]['html'] = '<input type="text" data-type="nummber"  id="'.$v['field'].'" name="'.$v['field'].'" maxlength="'.$v['max_length'].'" value="'.$value.'"/> &nbsp;  <span id="'.$v['field'].'Tip" style="color:red;"></span>'.$input_tips;
                    break;
                case 'floatnumber' :
                    $value = $value > 0 ? $value : ''; 
                    $field_list[$k]['html'] = '<input type="text" id="'.$v['field'].'" name="'.$v['field'].'" value="'.$value.'"/> &nbsp;  <span id="'.$v['field'].'Tip" style="color:red;"></span>'.$input_tips;
                    break;
                case 'address':
					if('add' == $type){
						$defaultinfo = unserialize(M('Config')->where('name = "defaultinfo"')->getField('value'));
						$state = $defaultinfo['state'];
						$city = $defaultinfo['city'];
						$area = $defaultinfo['area'];
					}else{
						$address_array = explode(chr(10),$value);
						$state = $address_array[0];
						$city = $address_array[1];
						$area = $address_array[2];
						$street = $address_array[3];
					}
					$field_list[$k]['html'] = '<script type="text/javascript">
					$(function(){
						new PCAS("'.$v['field'].'[\'state\']","'.$v['field'].'[\'city\']","'.$v['field'].'[\'area\']","'.$state.'","'.$city.'","'.$area.'");
					});
					</script><select name="'.$v['field'].'[\'state\']"  class="form-control"></select> 
						<select name="'.$v['field'].'[\'city\']"  class="form-control"></select>
						<select name="'.$v['field'].'[\'area\']"  class="form-control"></select>
						<input type="text" name="'.$v['field'].'[\'street\']" placeholder="'.L('THE STREET INFORMATION').'"  class="form-control" value="'.$street.'">';
					break;
                case 'p_box':
                        $str = '';
                        $category = M('product_category');
                        $category_list = $category->select();
                        $categoryList = getSubCategory(0, $category_list, '');
                        foreach ($categoryList as $v2) {
                            $checked = '';
                            if($v2['category_id'] == $value){
                                $checked = 'selected="selected"';
                            }
                            $str .= "<option $checked value=".$v2['category_id'].">".$v2['name']."</option>";
                            
                        }
                        $field_list[$k]['html'] = '<select id="'.$v['field'].'" name="'.$v['field'].'">'.$str.'</select> &nbsp;  <span id="'.$v['field'].'Tip" style="color:red;"></span>'.$input_tips;

                    break;
                case 'b_box':
                        $status = M('BusinessStatus')->order('order_id')->select();
                        $str = '';
                        foreach ($status as $v2) {
							$checked = '';
                            if($v2['status_id'] == $value){
                                $checked = 'selected="selected"';
                            }
                            $str .= "<option $checked value='".$v2['status_id']."'>".$v2['name']."</option>";
                        }
                        $field_list[$k]['html'] = '<select id="'.$v['field'].'" name="'.$v['field'].'">'.$str.'</select> &nbsp;  <span id="'.$v['field'].'Tip" style="color:red;"></span>'.$input_tips;
                    break;
                default: 
                    if ($v['field'] == 'create_time' || $v['field'] == 'update_time') {
                        break;
                    }else{
                        $customer_id = intval($_GET['customer_id']);
                        if($v['field'] == 'name' && $customer_id && $module == 'customer') $value=M('customer')->where('customer_id = %d', $customer_id)->getField('name');
                        $field_list[$k]['html'] = '<input type="text" id="'.$v['field'].'" name="'.$v['field'].'" maxlength="'.$v['max_length'].'" value="'.$value.'"/> &nbsp;  <span id="'.$v['field'].'Tip" style="color:red;"></span>'.$input_tips;
                    }
                    break;
            }
        }
        if($field_list[$k]['is_main'] == 1){
            $fieldlist['main'][] = $field_list[$k];
        }else{
            $fieldlist['data'][] = $field_list[$k];
        }
	}
	return $fieldlist;
}

//自定义字段html输出     $field为特殊验重字段   $d_module=($ModuelView) 
function field_list_mobile_html($type="add",$module="",$d_module=array()){
	if ($type == "add") {
		$field_list = M('Fields')->where('model = "'.$module.'" and in_add = 1')->order('order_id')->select();
	} else {
		$field_list = M('Fields')->where('model = "'.$module.'"')->order('order_id')->select();
	}
	
	foreach($field_list as $k=>$v){
		if(trim($v['input_tips'])){
			//$input_tips = ' &nbsp; <span style="color:#005580;">('.L('NOTE_').$v['input_tips'].')</span>';
			$input_tips = $v['input_tips'];
		}else{
			$input_tips = '';
		}
		if('add' == $type){
			$value = $v['default_value'];
		} elseif ('edit' == $type && !empty($d_module)) {
			$value = $d_module[$v['field']] !== '' ? $d_module[$v['field']] : '';
		}
		
		if($d_module['customer_id']){
			$customer_id = intval($d_module['customer_id']);
		}else{
			$customer_id = intval($_GET['customer_id']);
		}
		
		if($customer_id){
			$customer = M('customer')->where('customer_id = %d', $customer_id)->find();
			if($d_module['contacts_id']){
				$contacts = M('contacts')->where('contacts_id = %d', $d_module['contacts_id'])->find();
			}else{
				$contacts = M('contacts')->where('contacts_id = %d', $customer['contacts_id'])->find();
			}
		}
		if ($v['field'] == 'customer_id') {
			if($customer_id){					
				$field_list[$k]['html'] = '<input type="hidden" name="'.$v['field'].'" id="customer_id" value="'.$customer['customer_id'].'"/><input  type="text" name="customer_name"  class="form-control" id="customer_name" value="'.$customer['name'].'"/></br><a target="_blank" href="'.U('customer/add').'">'.L('CREATE NEW CUSTOMER').'</a>';
			}else{						
				$field_list[$k]['html'] = '<input type="hidden" name="'.$v['field'].'" id="customer_id"/><input  type="text" name="customer_name" id="customer_name"  class="form-control"></br><a target="_blank" href="add_customer:business">'.L('CREATE NEW CUSTOMER').'</a>';
			}
		}elseif($v['field'] == 'contacts_id'){
			if($customer_id){
				$field_list[$k]['html'] = '<input type="hidden" name="contacts_id" id="contacts_id" value="'.$contacts['contacts_id'].'"/><input   class="form-control" type="text" name="contacts_name" id="contacts_name" value="'.$contacts['name'].'"/>';
			}else{
				$field_list[$k]['html'] = '<input type="hidden" name="contacts_id" id="contacts_id"/><input  type="text" name="contacts_name"  class="form-control" id="contacts_name"/>';
			}
		}elseif($module == 'customer' && $v['field'] == 'tags'){
			//客户标签
			$tagsStr = substr($d_module['tags'], '1', strlen($d_module['tags'])-2);
			if($tagsStr !=''){
				$tagsName = M('tags')->where('tags_id in ( %s )', $tagsStr)->getField('name',true);
			}
			$field_list[$k]['html'] = '<input type="text" name="tags" id="tags"  class="form-control" value="'.implode(',', $tagsName).'" />';
		}else{
            switch ($v['form_type']) {
                case 'textarea' :
                    $field_list[$k]['html'] = '<textarea  rows="6"  placeholder="'.$input_tips.'"  class="form-control" id="'.$v['field'].'" name="'.$v['field'].'" >'.$value.'</textarea> &nbsp;  <span id="'.$v['field'].'Tip" style="color:red;"></span>';
                    break;
                case 'box' :

                /** wangchao  2016-04-16 **/
			
				$option_type = M('field_option')->where('field_id='.$v['field_id'])->field('field_type')->find();
				$option_values = M('field_option_value')->where('field_id='.$v['field_id'])->field('id,field_value,is_default_value')->order('order_id')->select();

				if($option_type['field_type'] == 1){	//raido 单选 
					$str = '';
					$str .= "<option value=''>--".L('PLEASE CHOOSE')."--</option>";
					foreach ($option_values as $key=>$vv) {		
							$str .= "<option value=".$vv['id'];
							$str .= $vv['is_default_value'] == 1  ? ' selected="selected" ':'';
							$str .= ">".$vv['field_value']."</option>";
					}
					$field_list[$k]['html'] = '<select  '.$required.' id="'.$v['field'].'" name="'.$v['field'].'"  class="form-control">'.$str.'</select>'.$input_tips;
					break;
				}else if($option_type['field_type'] == 2){	// checkbox 多选
					$str = '';
					$str .= "<option value=''>--".L('PLEASE CHOOSE')."--</option>";
					foreach ($option_values as $key=>$vv) {		
							$str .= "<option value=".$vv['id'];
							$str .= $vv['is_default_value'] == 1  ? ' selected="selected" ':'';
							$str .= ">".$vv['field_value']."</option>";
					}
					$field_list[$k]['html'] = '<select  '.$required.' id="'.$v['field'].'" name="'.$v['field'].'"  class="form-control">'.$str.'</select>'.$input_tips;
					break;
				}else if($option_type['field_type'] == 3){	//select 下拉
					$str = '';
					$str .= "<option value=''>--".L('PLEASE CHOOSE')."--</option>";
					foreach ($option_values as $key=>$vv) {		
							$str .= "<option value=".$vv['id'];
							$str .= $vv['is_default_value'] == 1  ? ' selected="selected" ':'';
							$str .= ">".$vv['field_value']."</option>";
					}
					$field_list[$k]['html'] = '<select  '.$required.' id="'.$v['field'].'" name="'.$v['field'].'"  class="form-control">'.$str.'</select>'.$input_tips;
					break;
				}
				break;

                case 'editor' :
                    /* $upload_url = U('file/editor');
					$fileManagerJson = U('file/manager');
                    $field_list[$k]['html'] = '<script type="text/javascript">
                    var editor;
                    KindEditor.ready(function(K) {
                        editor = K.create(\'textarea[name="'.$v['field'].'"]\', {
                            uploadJson:"'.$upload_url.'",
                            allowFileManager : true,
                            loadStyleMode : false,
							fileManagerJson: "'.$fileManagerJson.'"
                        });
                    });
                    </script>
                    <textarea name="'.$v['field'].'" id="'.$v['field'].'" style="width: 800px; height: 350px;">'.$value.'</textarea> &nbsp;  <span id="'.$v['field'].'Tip" style="color:red;"></span>';
                    break; */
					if($type == 'edit' ){
						$field_list[$k]['html'] = '<input type="text" readonly="true" placeholder="--暂不支持该类型--" />';
						break;
					}else{
						$field_list[$k]['html'] = '<textarea  rows="6"  placeholder="'.$input_tips.'"  class="form-control" id="'.$v['field'].'" name="'.$v['field'].'" >'.$value.'</textarea> &nbsp;  <span id="'.$v['field'].'Tip" style="color:red;"></span>';
						break;
					}
                case 'datetime' :
					if($v['field'] == 'nextstep_time'){
						$time_accuracy = 'yyyy-MM-dd HH:mm';
					}else{
						$time_accuracy = 'yyyy-MM-dd';
					}
                    $field_list[$k]['html'] = '<input readonly="true"  onFocus="WdatePicker({dateFmt:\''.$time_accuracy.'\'})" name="'.$v['field'].'" id="'.$v['field'].'" type="text"  class="form-control" value="'.pregtime($value).'"/></br><span id="'.$v['field'].'Tip" style="color:red;"></span>';
                    break;
                case 'number' :
                    $field_list[$k]['html'] = '<input type="text"  placeholder="'.$input_tips.'"   class="form-control" id="'.$v['field'].'" name="'.$v['field'].'" maxlength="'.$v['max_length'].'" value="'.$value.'"/></br><span id="'.$v['field'].'Tip" style="color:red;"></span>';
                    break;
                case 'floatnumber' :
                    $value = $value > 0 ? $value : ''; 
                    $field_list[$k]['html'] = '<input type="text" placeholder="'.$input_tips.'"  class="form-control" id="'.$v['field'].'" name="'.$v['field'].'" value="'.$value.'"/></br>  <span id="'.$v['field'].'Tip" style="color:red;"></span>';
                    break;
                case 'address':
					if('add' == $type){
						$defaultinfo = unserialize(M('Config')->where('name = "defaultinfo"')->getField('value'));
						$state = $defaultinfo['state'];
						$city = $defaultinfo['city'];
						$area = $defaultinfo['area'];
					}else{
						$address_array = explode(chr(10),$value);
						$state = $address_array[0];
						$city = $address_array[1];
						$area = $address_array[2];
						$street = $address_array[3];
					}
					$field_list[$k]['html'] = '<script type="text/javascript">
					$(function(){
						new PCAS("'.$v['field'].'[\'state\']","'.$v['field'].'[\'city\']","'.$v['field'].'[\'area\']","'.$state.'","'.$city.'","'.$area.'");
					});
					</script><select name="'.$v['field'].'[\'state\']"  class="form-control"></select> 
						<select name="'.$v['field'].'[\'city\']"  class="form-control"></select>
						<select name="'.$v['field'].'[\'area\']"  class="form-control"></select>
						<input type="text" name="'.$v['field'].'[\'street\']" placeholder="'.L('THE STREET INFORMATION').'" class="form-control" value="'.$street.'">';
					break;
                case 'p_box':
                        $str = '';
                        $category = M('product_category');
                        $category_list = $category->select();
                        $categoryList = getSubCategory(0, $category_list, '');
                        foreach ($categoryList as $v2) {
                            $checked = '';
                            if($v2['category_id'] == $value){
                                $checked = 'selected="selected"';
                            }
                            $str .= "<option $checked value=".$v2['category_id'].">".$v2['name']."</option>";
                            
                        }
                        $field_list[$k]['html'] = '<select style="width:80%" id="'.$v['field'].'" name="'.$v['field'].'">'.$str.'</select> &nbsp;  <span id="'.$v['field'].'Tip" style="color:red;"></span>'.$input_tips;

                    break;
                case 'b_box':
                        $status = M('BusinessStatus')->order('order_id')->select();
                        $str = '';
                        foreach ($status as $v2) {
							$checked = '';
                            if($v2['status_id'] == $value){
                                $checked = 'selected="selected"';
                            }
                            $str .= "<option $checked value='".$v2['status_id']."'>".$v2['name']."</option>";
                        }
                        $field_list[$k]['html'] = '<select style="width:80%" id="'.$v['field'].'" name="'.$v['field'].'">'.$str.'</select> &nbsp;  <span id="'.$v['field'].'Tip" style="color:red;"></span>'.$input_tips;
                    break;
                default: 
                    if ($v['field'] == 'create_time' || $v['field'] == 'update_time') {
                        break;
                    }else{
                        $customer_id = intval($_GET['customer_id']);
                        if($v['field'] == 'name' && $customer_id && $module == 'customer') $value=M('customer')->where('customer_id = %d', $customer_id)->getField('name');
                        $field_list[$k]['html'] = '<input type="text"  placeholder="'.$input_tips.'" id="'.$v['field'].'" name="'.$v['field'].'" maxlength="'.$v['max_length'].'" value="'.$value.'"/></br><span id="'.$v['field'].'Tip" style="color:red;"></span>';
                    }
                    break;
            }
        }
        if($field_list[$k]['is_main'] == 1){
            $fieldlist['main'][] = $field_list[$k];
        }else{
            $fieldlist['data'][] = $field_list[$k];
        }
	}
	return $fieldlist;
}

/*
	返回码说明 短信函数返回1发送成功  0进入审核阶段 -4手机号码不正确
*/
//单条短信
//发送到目标手机号码 $telphone手机号码 $message短信内容
function sendSMS($telphone, $message, $sign_name="sign_name",$sendtime=''){
	$flag = 0; 
	$sms = F('sms');
	$argv = array( 
		'sn'=>$sms['uid'],
		'pwd'=>strtoupper(md5($sms['uid'].$sms['passwd'])),
		'mobile'=>$telphone,
		'content'=>urlencode($message.'【'.$sms[$sign_name].'】'),
		'ext'=>'',
		'rrid'=>'',
		'stime'=>$sendtime
	); 
	foreach ($argv as $key=>$value) { 
		if ($flag!=0) { 
			$params .= "&"; 
			$flag = 1; 
		} 
		$params.= $key."="; $params.= urlencode($value); 
		$flag = 1; 
    } 
	$length = strlen($params); 
	$fp = fsockopen("sdk2.entinfo.cn",8060,$errno,$errstr,10) or exit($errstr."--->".$errno); 
	$header = "POST /webservice.asmx/mdSmsSend_u HTTP/1.1\r\n"; 
	$header .= "Host:sdk2.entinfo.cn\r\n"; 
	$header .= "Content-Type: application/x-www-form-urlencoded\r\n"; 
	$header .= "Content-Length: ".$length."\r\n"; 
	$header .= "Connection: Close\r\n\r\n"; 
	$header .= $params."\r\n"; 
	fputs($fp,$header); 
	$inheader = 1; 
	while (!feof($fp)) { 
		$line = fgets($fp,1024);
		if ($inheader && ($line == "\n" || $line == "\r\n")) { 
			$inheader = 0; 
		} 
		if ($inheader == 0) { 
		} 
	} 


	preg_match('/<string xmlns=\"http:\/\/tempuri.org\/\">(.*)<\/string>/',$line,$str);
	$result=explode("-",$str[1]);


	   
	if(count($result)>1){
		//echo '发送失败返回值为:'.$line."请查看webservice返回值";
		return $line;
	}else{
		//echo '发送成功 返回值为:'.$line;  
		return 1;
	}
}
function sendtestSMS($uid, $uname, $telphone){
	$flag = 0; 
	$sms = F('sms');
	$argv = array( 
		'sn'=>$uid,
		'pwd'=>strtoupper(md5($uid.$uname)),
		'mobile'=>$telphone,
		'content'=>urlencode('TEST SMS 【smartcrm】'),
		'ext'=>'',
		'rrid'=>'',
		'stime'=>$sendtime
	); 
	foreach ($argv as $key=>$value) { 
		if ($flag!=0) { 
			$params .= "&"; 
			$flag = 1; 
		} 
		$params.= $key."="; $params.= urlencode($value); 
		$flag = 1; 
    } 
	$length = strlen($params); 
	$fp = fsockopen("sdk2.entinfo.cn",8060,$errno,$errstr,10) or exit($errstr."--->".$errno); 
	$header = "POST /webservice.asmx/mdSmsSend_u HTTP/1.1\r\n"; 
	$header .= "Host:sdk2.entinfo.cn\r\n"; 
	$header .= "Content-Type: application/x-www-form-urlencoded\r\n"; 
	$header .= "Content-Length: ".$length."\r\n"; 
	$header .= "Connection: Close\r\n\r\n"; 
	$header .= $params."\r\n"; 
	fputs($fp,$header); 
	$inheader = 1; 
	while (!feof($fp)) { 
		$line = fgets($fp,1024);
		if ($inheader && ($line == "\n" || $line == "\r\n")) { 
			$inheader = 0; 
		} 
		if ($inheader == 0) { 
		} 
	} 
	preg_match('/<string xmlns=\"http:\/\/tempuri.org\/\">(.*)<\/string>/',$line,$str);
	$result=explode("-",$str[1]);
	if(count($result)>1){
		//echo '发送失败返回值为:'.$line."请查看webservice返回值";
		return $line;
	}else{
		//echo '发送成功 返回值为:'.$line;  
		return 1;
	}
}

//多条短信 最多600条
//发送到目标手机号码字符串 用","隔开 $telphone手机号码 $message短信内容 
function sendGroupSMS($telphone, $message, $sign_name="sign_name",$sendtime=''){
	$flag = 0; 
	$sms = F('sms');
    //要post的数据 
	$argv = array( 
		'sn'=>$sms['uid'], ////替换成您自己的序列号
		'pwd'=>strtoupper(md5($sms['uid'].$sms['passwd'])), //此处密码需要加密 加密方式为 md5(sn+password) 32位大写
		'mobile'=>$telphone,//手机号 多个用英文的逗号隔开 post理论没有长度限制.推荐群发一次小于等于10000个手机号
		'content'=>urlencode($message.'【'.$sms[$sign_name].'】'),//短信内容
		'ext'=>'',
		'rrid'=>'',//默认空 如果空返回系统生成的标识串 如果传值保证值唯一 成功则返回传入的值
		'stime'=>$sendtime//定时时间 格式为2011-6-29 11:09:21
	); 
	//构造要post的字符串 
	foreach ($argv as $key=>$value) { 
		if ($flag!=0) { 
			$params .= "&"; 
			$flag = 1; 
		} 
		$params.= $key."="; $params.= urlencode($value); 
		$flag = 1; 
    } 
	$length = strlen($params); 
		 //创建socket连接 
	$fp = fsockopen("sdk2.entinfo.cn",8060,$errno,$errstr,10) or exit($errstr."--->".$errno); 
	//构造post请求的头 
	$header = "POST /webservice.asmx/mdSmsSend_u HTTP/1.1\r\n"; 
	$header .= "Host:sdk2.entinfo.cn\r\n"; 
	$header .= "Content-Type: application/x-www-form-urlencoded\r\n"; 
	$header .= "Content-Length: ".$length."\r\n"; 
	$header .= "Connection: Close\r\n\r\n"; 
	//添加post的字符串 
	$header .= $params."\r\n"; 
	//发送post的数据 
	fputs($fp,$header); 
	$inheader = 1; 
	while (!feof($fp)) { 
		$line = fgets($fp,1024); //去除请求包的头只显示页面的返回数据 
		if ($inheader && ($line == "\n" || $line == "\r\n")) { 
			$inheader = 0; 
		} 
		if ($inheader == 0) { 
			// echo $line; 
		} 
	} 


	preg_match('/<string xmlns=\"http:\/\/tempuri.org\/\">(.*)<\/string>/',$line,$str);
	$result=explode("-",$str[1]);


	   
	if(count($result)>1){
		//echo '发送失败返回值为:'.$line."请查看webservice返回值";
		return $line;
	}else{
		//echo '发送成功 返回值为:'.$line;  
		return 1;
	}
}
 function getSmsNum(){
	$sms = F('sms');
	
	$flag = 0; 
        //要post的数据 
	$argv = array( 
		'sn'=>$sms['uid'], //替换成您自己的序列号
		'pwd'=>$sms['passwd'],//替换成您自己的密码	
	); 
	//构造要post的字符串 
	foreach ($argv as $key=>$value) { 
		if ($flag!=0) { 
				 $params .= "&"; 
				 $flag = 1; 
		} 
		$params.= $key."="; $params.= urlencode($value); 
		$flag = 1; 
	} 
		$length = strlen($params); 
		 //创建socket连接 
		$fp = fsockopen("sdk2.entinfo.cn",8060,$errno,$errstr,10) or exit($errstr."--->".$errno); 
		//构造post请求的头 
		$header = "POST /webservice.asmx/GetBalance HTTP/1.1\r\n"; 
		$header .= "Host:sdk2.entinfo.cn\r\n"; 
		$header .= "Content-Type: application/x-www-form-urlencoded\r\n"; 
		$header .= "Content-Length: ".$length."\r\n"; 
		$header .= "Connection: Close\r\n\r\n"; 
		//添加post的字符串 
		$header .= $params."\r\n"; 
		//发送post的数据 
		fputs($fp,$header); 
		$inheader = 1; 
		while (!feof($fp)) { 
			$line = fgets($fp,1024); //去除请求包的头只显示页面的返回数据 
				if ($inheader && ($line == "\n" || $line == "\r\n")) { 
				$inheader = 0; 
			} 
			if ($inheader == 0) { 
				// echo $line; 
			} 
		} 
		//<string xmlns="http://tempuri.org/">-5</string>
		$line=str_replace("<string xmlns=\"http://tempuri.org/\">","",$line);
		$line=str_replace("</string>","",$line);
		$result=explode("-",$line);
		if(count($result)>1)
			return $line;
		else
			return $line;
}
//判断目录是否可写
function check_dir_iswritable($dir_path){
    $dir_path=str_replace('\\','/',$dir_path);
    $is_writale=1;
    if(!is_dir($dir_path)){
        $is_writale=0;
        return $is_writale;
    }else{
        $file_hd=@fopen($dir_path.'/test.txt','w');
        if(!$file_hd){
            @fclose($file_hd);
            @unlink($dir_path.'/test.txt');
            $is_writale=0;
            return $is_writale;
        }
        @unlink($dir_path.'/test.txt');
        $dir_hd=opendir($dir_path);
        while(false!==($file=readdir($dir_hd))){
            if ($file != "." && $file != "..") {
                if(is_file($dir_path.'/'.$file)){
                    //文件不可写，直接返回
                    if(!is_writable($dir_path.'/'.$file)){
                        return 0;
                    } 
                }else{
                    $file_hd2=@fopen($dir_path.'/'.$file.'/test.txt','w');
                    if(!$file_hd2){
                        @fclose($file_hd2);
                        @unlink($dir_path.'/'.$file.'/test.txt');
                        $is_writale=0;
                        return $is_writale;
                    }
                    @unlink($dir_path.'/test.txt');
                    //递归
                    $is_writale=check_dir_iswritable($dir_path.'/'.$file);
                }
            }
        }
    }
return $is_writale;
}

function is_email($email)
{
	//$pattern = "/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i";
	$pattern = "/^[-_+.[:alnum:]]+@((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+([a-z]{2,4})|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i";
	return strlen($email) > 7 && preg_match($pattern, $email);
}
function is_phone($phone)
{
	return strlen(trim($phone)) == 11 && preg_match("/^1[3|5|7|8][0-9]{9}$/i", trim($phone));
}
function pregtime($timestamp){
	if($timestamp){
		return date('Y-m-d',$timestamp);
	}else{
		return '';
	}
}


function userLog($uid,$text=''){
    $user = M('user')->where(array('user_id'=>$uid))->find();
    $category = $user['category_id'] == 1 ? L('ADMIN') : L('USER');
    $data['user_id'] = $uid;
	$data['module_name'] = strtolower(MODULE_NAME);
    $data['action_name'] = strtolower(ACTION_NAME);
    $data['create_time'] = time();
 //   $data['action_id'] = $id;
    $data['content'] = sprintf('%s%s在%s%s。%s',$category,$user['name'],date('Y-m-d H:i:s'),L(ACTION_NAME),$text);
    $userLog = M('userLog');
    $userLog->create($data);
    if($userLog->add()){return true;}else{return false;}
    
}
function vali_permission($m, $a){
	$allow = $params['allow'];
	
	if (session('?admin')) {
		return true;
	}
	if (in_array($a, $allow)) {
		return true;
	} else {
		switch ($a) {
			case "listdialog" : $a = 'index'; break;
			case "adddialog" : $a = 'add'; break;
			case "excelimport" : $a = 'add'; break;
			case "excelexport" : $a = 'view'; break;
			case "cares" :  $a = 'index'; break;
			case "caresview" :  $a = 'view'; break;
			case "caresedit" :  $a = 'edit'; break;
			case "caresdelete" :   $a = 'delete'; break;
			case "caresadd" :  $a = 'add'; break;
			case "receive" : $a = 'add'; break;
			case "role_add" : $a = 'add';break;
			case "sendsms" : $a = 'marketing';break;
			case "sendemail" : $a = 'marketing';break;
		}
		$url = strtolower($m).'/'.strtolower($a);
		$ask_per = M('permission')->where('url = "%s" and role_id = %d', $url, session('role_id'))->find();
		if (is_array($ask_per) && !empty($ask_per)) {
			return true;
		} else {
			return false;
		}
	}
}
/**
 * @ atuhor		: Lynn
 * @ function 	: formmat the print_r to debug the array conveniently
 **/
function println($data, $offset=true){
	if(empty($data)){
		echo '<pre>返回数据为空！</pre>';
	}else{
		echo '<pre>'; print_r($data); echo '</pre>';
	}
	if($offset){
		die;
	}
}

/**
 * @ atuhor		: zf
 * @ function 	: 验证某条数据的权限
 **/
function check_permission($module_id, $module, $permission_field='owner_role_id'){
	$role_id = intval(session('role_id'));
	$owner_role_id = M($module)->where($module.'_id = %d', $module_id)->getField($permission_field);
	$permission_ids = getSubRoleId();
	if(in_array($owner_role_id, $permission_ids) || !$owner_role_id) return true;
	else return false;
}

/**
 * @ atuhor		: zf
 * @ function 	: 下载方法
 **/
 function download($file,$name=''){
    $fileName = $name ? $name : pathinfo($file,PATHINFO_FILENAME);
    $filePath = realpath($file);
    
    $fp = fopen($filePath,'rb');
    
    if(!$filePath || !$fp){
        header('HTTP/1.1 404 Not Found');
        echo "Error: 404 Not Found.(server file path error)<!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding -->";
        exit;
    }
    
    $fileName = $fileName .'.'. pathinfo($filePath,PATHINFO_EXTENSION);
    $encoded_filename = urlencode($fileName);
    $encoded_filename = str_replace("+", "%20", $encoded_filename);
    
    header('HTTP/1.1 200 OK');
    header( "Pragma: public" );
    header( "Expires: 0" );
    header("Content-type: application/octet-stream");
    header("Content-Length: ".filesize($filePath));
    header("Accept-Ranges: bytes");
    header("Accept-Length: ".filesize($filePath));
    
    $ua = $_SERVER["HTTP_USER_AGENT"];
    if (preg_match("/MSIE/", $ua)) {
        header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
    } else if (preg_match("/Firefox/", $ua)) {
        header('Content-Disposition: attachment; filename*="utf8\'\'' . $fileName . '"');
    } else {
        header('Content-Disposition: attachment; filename="' . $fileName . '"');
    }
    
    // ob_end_clean(); <--有些情况可能需要调用此函数
    // 输出文件内容
    fpassthru($fp);
    exit;
 }
 
 /**
  * @author		: myron
  * @function	: 获取表信息
  * @table_name	: 表名(不含表前缀)
  **/
function getTableInfo($table_name){
	$sql = 'SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = "'.C('DB_NAME').'" and table_name LIKE "'.C('DB_PREFIX').$table_name.'"';
	$result = M('')->query($sql);
	return $result;
}

//filemanager排序
function cmp_func($a, $b) {
	global $order;
	if ($a['is_dir'] && !$b['is_dir']) {
		return -1;
	} else if (!$a['is_dir'] && $b['is_dir']) {
		return 1;
	} else {
		if ($order == 'size') {
			if ($a['filesize'] > $b['filesize']) {
				return 1;
			} else if ($a['filesize'] < $b['filesize']) {
				return -1;
			} else {
				return 0;
			}
		} else if ($order == 'type') {
			return strcmp($a['filetype'], $b['filetype']);
		} else {
			return strcmp($a['filename'], $b['filename']);
		}
	}
}


/**
 * @ atuhor		: zf
 * @ function 	: 判断有无具体操作的权限  返回值为权限类型
 * @ return 	: 返回值为权限类型  1、自己和下属  2、所有人 3、仅自己  4、部门所有人
 * @ des	 	: 参数说明：
 *                $module 对应的模块名 小写
 *                $action 对应的方法名
 **/
function getCheckUrlByAction($m, $a){
	switch (strtolower($a)) {
		case "listdialog" : $a = 'index'; break;
		case "radiolistdialog" : $a = 'index'; break;
		case "checklistdialog" : $a = 'index'; break;
		case "changedialog" : $a = 'index'; break;
		case "adddialog" : $a = 'add'; break;
		case "cares" :  $a = 'index'; break;
		case "excelimportdownload" : $a = 'excelimport'; break;
		case "receive" : $a = 'add'; break;
		case "search" : $a = 'index'; break;
		case "role_add" : $a = 'add';break;
		case "remove" : $a = 'edit';break;
		case "changecontent" : $a = 'index';break;
		case "advance" : $a = 'edit';break;
		case "close" : $a = 'edit';break;
		case "revert" : $a = 'delete';break;
		case "getcustomerlist" : $a = 'index';break;
		case "fenpei" : $a = 'add';break;
		case "getwarehouselist" : $a = 'warehouse';break;
		case "salesreturn" : $a = 'index'; break;
		case "addsalesreturn" : $a = 'add'; break;
		case "editsalesreturn" : $a = 'edit'; break;
		case "changetofirstcontact" : $a = 'edit'; break;
		case "addcategory" : 
		case "editcategory" : 
			if(strtolower($m) == 'supplier'){
				$a = 'category';
			}
			break;
		case "revokecheck" : $a = 'check'; break;
		default: $a = strtolower($a); break;
	}
	return strtolower($m.'/'.$a);
}

/**
 * @ atuhor		: zf
 * @ function 	: 判断有无具体操作的权限  返回值为权限类型
 * @ return 	: 返回值为权限类型  1、自己和下属  2、所有人 3、仅自己  4、部门所有人
 * @ des	 	: 参数说明：
 *                $module 对应的模块名 小写
 *                $action 对应的方法名
 **/
function checkPerByAction($m, $a){
	$m_permission = M('permission');
	$url = getCheckUrlByAction($m, $a);
	
	if(session('?admin') ){
		//2为所有人
		return 2;
	}elseif($per = $m_permission->where('url = "%s" and role_id = %d', $url, session('role_id'))->find()){	
//echo 2;die;
		//有$url操作权限；
		return $per['type'];
	}else{
//echo 34;die;
		//无$url操作权限；
		return 0;
	}
}



/**
 * @ atuhor		: zf
 * @ function 	: 获取权限范围内roleid
 * @ return 	: 返回roleid的数组
 * @ des	 	: 参数说明：
 *                $module 对应的模块名 小写
 *                $action 对应的方法名
 *                $sub_role 为true的话 返回权限范围内的下属roleid
 *                          为false 返回权限范围内的roleid
 **/
function getPerByAction($m, $a, $sub_role=false){
	$m_permission = M('permission');	
	$url = getCheckUrlByAction($m, $a);
	
	$per_type =  M('Permission') -> where('role_id = %d and url = "%s"', session('role_id'), $url)->getField('type');
	if($sub_role){
		if($per_type == 3){
			$below_ids = array();
		}elseif($per_type == 4){
			$departmen_role_ids = array();
			$role_ids = getRoleByDepartmentId(session('department_id'), true);
			foreach($role_ids as $v){
				$departmen_role_ids[] = $v['role_id'];
			}
			$temp_below_ids = getSubRoleId(false);
			$below_ids = array_intersect($departmen_role_ids, $temp_below_ids);
		}else{
			$below_ids = getSubRoleId(false);
			
		}		
		if(empty($below_ids))
			return array(-1);
		else
			return $below_ids;
	}else{
		//管理员拥有所有人的数据权限
		if(session('?admin')) return getSubRoleId(true, 1);
		$role_array = array();
	
		switch($per_type){
			//权限类型为1 包含自己和下属的数据 返回自己和下属role_id数组
			case 1: $role_array = getSubRoleId(); break;
			//权限类型为2 返回false 不加判断条件即所有人都有的权限。
			case 2: $role_array = getSubRoleId(true, 1); break;
			//权限类型为3 仅自己的数据 返回数组 返回仅包含自己role_id的数组
			case 3: $role_array = array(session('role_id')); break;
			//默认 部门所有人 
			case 4: 
				$role_ids = getRoleByDepartmentId(session('department_id'), true);
				foreach($role_ids as $v){
					$role_array[] = $v['role_id'];
				}
				break;
		}
		return $role_array;
	}
}

/**
 * @ atuhor		: zf
 * @ function 	: 根据操作权限获取roleid
 * @ return 	: 返回roleid的数组
 * @ des	 	: 参数说明：
 *                $per_array为包含操作的数组 array('leads/add', 'customer/add')
 **/
function getRoleByPer($per_array){
	if($per_array){
		$where['url'] = array('in', $per_array);
		if($role_ids = M('Permission') -> where($where)->getField('role_id', true)){
			$role_ids_array = D('RoleView')->where('role.role_id in(%s)', implode(',', $role_ids))->getField('role_id', true);
			return array_unique($role_ids_array);
		}else{
			return false;
		}
	}else{
		return false;
	}
}

/**
 * @ atuhor		: zf
 * @ function 	: 根据当前处理程序判断顶部菜单按钮项
 * @ return 	: 返回顶部的数组
 * @ des	 	: 参数说明：
 *                $module_name为模块名, $action_name为方法名
 **/
function setSelectedMenu($module_name, $action_name){
	$module_name = strtolower($module_name);
	$action_name = strtolower($action_name);
	if($action_name == 'analytics'){
		return 'menu_analy';
	}elseif($action_name == 'sendsms' || $action_name == 'sendemail' || $action_name == 'smsregetUserListd'){
		return 'menu_market';
	}
	switch($module_name){
		case 'leads':
		case 'customer':
			return 'menu_customer';
		case 'business':
		case 'contract':
			return 'menu_business';
		case 'product':
		case 'sales':
		case 'stock':
		case 'supplier':
		case 'purchase':
		case 'contract':
			return 'menu_stock';
		case 'finance':
			return 'menu_finance';
		case 'task':
		case 'knowledge':
		case 'log':
		case 'event':
		case 'user':
		case 'examine':
		case 'workorder':
		case 'announcement':
			return 'menu_office';
		case 'actionlog':
		case 'setting':
			return 'menu_setting';
		case 'message':
			return 'menu_home';
		default : return 'index';
	}
}

function getSubCategoryTreeCode($category_id, $first=0) {
	$string = "";
	$department_list = M('ProductCategory')->where('parent_id = %d', $category_id)->select();
	if ($department_list) {
		if ($first) {
			$string = '<ul id="browser" class="filetree"><li style="list-style-type: none;" class="collapsable"><span rel="0" class="folder ta">全部 &nbsp; <span class="" id="0"> </span></span></li>';
		} else {
			$string = "<ul>";
		}
		foreach($department_list AS $value) {
			if($first){
				$string .= "<li style='list-style-type: none;'><span rel='".$value['category_id']."' class='folder ta'>".$value['name']." &nbsp; <span class='' id='".$value['category_id']."'> </span></span>".getSubCategoryTreeCode($value['category_id'])."</li>";
			} else {
				$string .= "<li style='list-style-type: none;'><span rel='".$value['category_id']."' class='file ta'>".$value['name']." &nbsp; <span class='' id='".$value['category_id']."'> </span></span>".getSubCategoryTreeCode($value['category_id'])."</li>";
			}		
		}
		$string .= "</ul>";
	} 
	return $string;
}

/**
 * author : myrom
 * function : 截取字符长度，如果超过字符长度，后面追加...
 * @str : 要截取的字符串  $len : 要截取的长度
 **/
function cutString($str='', $len='15'){
	if(empty($str) || empty($len)) return false;
	$pre_content = strip_tags($str);
	$pre_content_len = mb_strlen($pre_content,'utf-8');
	if($pre_content_len <= $len){
		return $pre_content;
	}else{
		$pre_content = mb_substr($pre_content,0,$len,'utf-8');
		return $pre_content.' . . .';
	}
}

/**
 * author : myron
 * function : 在AuthenticateBehavior中判断是否AJAX请求，如果是AJAx请求且在弹窗页没有权限，直接显示无权限
 **/ 
function isAjaxRequest() {
	if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) ) {
		if('xmlhttprequest' == strtolower($_SERVER['HTTP_X_REQUESTED_WITH'])){
			return true;
		}	
	}
	if(!empty($_POST[C('VAR_AJAX_SUBMIT')]) || !empty($_GET[C('VAR_AJAX_SUBMIT')])){
		// 判断Ajax方式提交
		return true;
	}
	return false;
}

/**
 * author : myron
 * function : 读取标签
 * param 	: limit 显示条数。如果没有limit，默认读取所有标签并以热度排序。如果有limit，读取限制条数的标签，并以热度排序
 **/ 
function getTags($limit){
	$m_tags = M('tags');
	if(!empty($limit)){
		$tags = $m_tags->limit($limit)->order('hits desc')->select();
	}else{
		$tags = $m_tags->order('hits desc')->select();
	}
	return $tags;
}

/**
 * author : myron
 * function : App推送
 * param 	: limit 
 type = 1 推送单个设备
 type = 2 推送多个设备
 model_type = 1 IOS
 model_type = 2 Android
 **/
/*  function Xinge($token,$title,$content,$type,$model_type){
	$access_id = '';
	$secret_key = '';
	import('@.ORG.XingeApp');
	if($model_type == 1){
		$environment = 0;
		if($type == 1){
			foreach($token as $v){
				$token = $v;
			}
			$result = XingeApp::PushTokenIos($access_id,$secret_key,$content,$token,XingeApp::IOSENV_DEV);
		}else{
			$push = new XingeApp($access_id,$secret_key);
			$mess = new Message(); //$mess = new MessageIOS();
			//完善Message消息 
			$mess->setExpireTime(86400);
			$mess->setTitle($title);
			$mess->setContent($content);
			$mess->setType(Message::TYPE_NOTIFICATION);
			$ret = $push->CreateMultipush($mess, XingeApp::IOSENV_DEV);
			if($ret['ret_code'] == 0){
				$pushId = $ret['result']['push_id'];
				//推送消息给大批量设备，数量有限（1000个）(可多次)
				foreach($token as $v){
					if($v != ''){
						$tokenlist[] = $v;
					}
				}
				$token_list = array_chunk($tokenlist, 1000); //拆分数组
				foreach($token_list as $k=>$v){
					$push = new XingeApp($access_id,$secret_key);
					$result = $push->PushDeviceListMultiple($pushId,$v);
				}
			}
		}
	}elseif($model_type == 2){
		if($type == 1){
			XingeApp::PushTokenAndroid($access_id,$secret_key,$title,$content,$token);
		}else{
			$push = new XingeApp($access_id,$secret_key);
			$mess = new Message(); //$mess = new MessageIOS();
			//完善Message消息 
			$mess->setExpireTime(86400);
			$mess->setTitle($title);
			$mess->setContent($content);
			$mess->setType(Message::TYPE_NOTIFICATION);
			$ret = $push->CreateMultipush($mess, XingeApp::IOSENV_DEV);
			if($ret['ret_code'] == 0){
				$pushId = $ret['result']['push_id'];
				//推送消息给大批量设备，数量有限（1000个）(可多次)
				foreach($token as $v){
					if($v != ''){
						$tokenlist[] = $v;
					}
				}
				$token_list = array_chunk($tokenlist, 1000); //拆分数组
				foreach($token_list as $k=>$v){
					$push = new XingeApp($access_id,$secret_key);
					$result = $push->PushDeviceListMultiple($pushId,$v);
				}
			}
		}
	}
 } */
 function redirects($string="",$url=""){
	if($string == ""){
		if($url == ""){
			die("<meta charset='utf-8'><Script charset='UTF-8'  Language='JavaScript'>history.back(-1);</Script>");
		}else{
			die("<meta charset='utf-8'><Script charset='UTF-8'  Language='JavaScript'>window.location.href='".$url."';</Script>");
		}
	}else{
		if($url == ""){
			die("<meta charset='utf-8'><Script charset='UTF-8' Language='JavaScript'>alert('".$string."');history.back(-1);</Script>");
		}else{
			die("<meta charset='utf-8'><Script charset='UTF-8' Language='JavaScript'>alert('".$string."');window.location.href='".$url."';</Script>");
		}
	}
}
//自定义字段验重
//params : field 字段名, val 值 ,id 排除当前数据验重,model = 需要查询的模块名
function validate($model,$field,$val,$id) {
	if(!$field || !$val){
		return false;
	}
	$field_info = M('Fields')->where('model = "%s" and field = "%s"',$model,$field)->find();
	if($model == 'contacts'){
		$m_fields = $field_info['is_main'] ? D('contacts') : D('ContactsData');
	}elseif($model == 'customer'){
		$m_fields = $field['is_main'] ? D('Customer') : D('CustomerData');
	}elseif($model == 'business'){
		$m_fields = $field['is_main'] ? D('Business') : D('BusinessData');
	}elseif($model == 'product'){
		$m_fields = $field['is_main'] ? D('Product') : D('ProductData');
	}elseif($model == 'leads'){
		$m_fields = $field['is_main'] ? D('Leads') : D('LeadsData');
	}
	$where[$field] = array('eq',$val);
	if($id){
		$where[$m_fields->getpk()] = array('neq',$params['id']);
	}
	if($fields){
		if ($m_fields->where($where)->find()) {
			return true;
		} else {
			return false;
		}
	}else{
		return false;
	}
}
//APP列表添加权限判断接口
function apppermission($m,$a){
	if(session('?admin')){
		$permission = array();
		$permission['add'] = 1;
		return $permission;
	}else{
		$m_permission = M('Permission');
		//$url = getCheckUrlByAction($m,$a);
		//$arr = explode('/',$url);
		$where['url'] = array('like','%'.$m.'%');
		$where['role_id'] = session('role_id');
		$permission_list = $m_permission->where($where)->select();
		foreach($permission_list as $k=>$v){
			$permission_info = explode('/',$v['url']);
			if($permission_info[1] == 'add'){
				$permission['add'] = 1;
				break;
			}else{
				$permission['add'] = 0;
			}
		}
		return $permission;
		//echo json_encode(array('status'=>-2,'info'=>'您没有此权利!'));die();
	}
}
/**
 * author : xiaoxu
 * function : app列表权限返回
 * param 	: $m=MODULE_NAME $role_id 岗位ID $type=1 有role_id判断 $type=2 没有role_id 判断
 **/
function permissionlist($m,$role_id,$type){
	if(session('?admin')){
		$permission = array();
		$permission['edit'] = 1;
		$permission['view'] = 1;
		$permission['delete'] = 1;
		return $permission;
	}else{
		$list = array('view','edit','delete');
		$permission = array();
		foreach($list as $k=>$v){
			if($v == 'view'){
				$all_ids = getPerByAction($m,'view');
				if(in_array($role_id, $all_ids)){
					$permission['view'] = 1;
				}
			}elseif($v == 'edit'){
				$all_ids = getPerByAction($m,'edit');
				if(in_array($role_id, $all_ids)){
					$permission['edit'] = 1;
				}
			}elseif($v == 'delete'){
				$all_ids = getPerByAction($m,'delete');
				if(in_array($role_id, $all_ids)){
					$permission['delete'] = 1;
				}
			}
		}
		return (object)$permission;
	}
}
//非role_id权限判断接口
function getpermission($m){
	if(session('?admin')){
		$permission = array();
		$permission['edit'] = 1;
		$permission['view'] = 1;
		$permission['delete'] = 1;
		return $permission;
	}else{
		$m_permission = M('Permission');
		$where['url'] = array('like','%'.$m.'%');
		$where['role_id'] = session('role_id');
		$permission_list = $m_permission->where($where)->select();
		$permission = array();
		foreach($permission_list as $k=>$v){
			$permission_info = explode('/',$v['url']);
			if(in_array($permission_info[1], array('edit','view','delete'))){
				$permission[$permission_info[1]] = 1;
			}
		}
		return $permission;
	}
}
/**
 * author : dongjun
 * function : 将数组转成x-editable的box类型的JSON格式
 * param 	: $array
 **/
function transEditableBoxJson($source)
{
	if(!is_array($source))
	{
	  return false;	
	}
	$result =  array(array('text'=>'','value'=>''));
	foreach($source as $k=>$v)
	{
	  array_push($result,array('text'=>$v,'value'=>$k));
	}
	return $result;
}
/**
 *  author : dongjun
 *  function : 生成图形格式
 *  param 	: $array
 **/
function getFalshXml($title,$data,$x)
{
  if(!is_array($title) ||!is_array($data) ||$x =="") return false;
  $count = count($data);
  for($i = 0 ;$i<$count;$i++){
		foreach($title as $k=>$v){
			if($i == 0){
				switch($v[1]){
					case '个':
						$numberScaleValue = "1";
						$numberScaleUnit = "个";
					break;
					case '通':
						$numberScaleValue = "1";
						$numberScaleUnit = "通";
					break;
					case '%':
						$numberScaleValue = "0.01";
						$numberScaleUnit = "％";
					break;
					case '秒':
						$numberScaleValue = "1,60,60,24,7";
						$numberScaleUnit = "秒,分钟,小时,天,星期";
					break;
					default :
						$numberScaleValue = "1";
						$numberScaleUnit = "个";
					break;
				}
				  $xml[$k] = "<graph caption=\'".$v['0']."\' xAxisName=\'\' yAxisName=\'\' formatNumberScale=\'1\' numberPrefix=\'\' numberSuffix=\'\'  numberScaleValue=\'".$numberScaleValue ."\' numberScaleUnit=\'".$numberScaleUnit."\'  showNames=\'1\'  showValues=\'1\' outCnvBaseFontSize=\'13\' baseFontSize=\'12\' captionFontSize=\'12\'>";
			 }
			$value = strpos($k,'_format')  >0  ?$data[$i][str_replace('_format','',$k)] : $data[$i][$k];
			$xml[$k] .= "<set name=\'".$data[$i][$x]."\' value=\'".$value."\' colo=\'AFD8F8\' />";
			if($i == $count -1){
				$xml[$k] .= "</graph>";
			}
		}
  }
  return $xml;
}

function trans_to_format($array,$sep='format')
{
	if(!is_array($array)) return $array;
	$result = array();
	foreach($array as $key=>$info)
	{
		$temp = array();
		foreach($info as $k=>$v)
		{
			if(strpos($k,$sep) !== false)
			{
			   	$temp[$k] = sprintf("%01.2f", $v*100).'%';
			}else{
			  $temp[$k] = $v;
			}
		}
		$result[$key] = $temp; 
	}
	return $result;
}

/**
 *  author   : wangchao
 *  function : 生成jQgrid的搜索数据字符串
 *  param 	 : $array,$array,$string
 *  date     : 2016-04-16
 */
function jQgrid_colModel($field_list_all,$v,$acname)
{  
  $colModel  ="{";
  $colModel .="name:'".$v['field']."',";
  $colModel .="index:'".$v['field']."',";
  $colModel .="editable:true,";
  if(!!$acname[$v['field']])
  {
	 $colModel .="formatter:Fmatter".$acname[$v['field']]; 
  }else{
	if($v['form_type'] == "user" ){
		  $colModel .="formatter:FmatterUserName,";
	}else if($v['form_type'] == "datetime" ){
		  $colModel .="sorttype : 'date',";
		  $colModel .= jQgrid_searchBar('datetime',$v['field']);
	}else if($v['form_type'] == 'box'){
		$option_values = M('field_option_value')->where('field_id='.$v['field_id'])->field('id,field_value')->order('order_id')->select();
		$arr = array();
		foreach( $option_values as $v){
			$arr[$v['id']] = L($v['field_value']);
		}
		//dump($arr);
		$colModel .= jQgrid_searchBar('select',$arr);
	}

  }
  $colModel .="},";	
  return $colModel;	
}
/**
 *  author : dongjun
 *  function : 生成jQgrid的搜索数据字符串
 *  param 	: $string,$mix
         老的，jquery自带的
         $json_str .= "numberOfMonths:1,";//显示几个月
		 $json_str .= "showButtonPanel:true,";//是否显示按钮面板
		 $json_str .= "dateFormat: 'yy-mm-dd',";//日期格式
		 $json_str .= "clearText:'清除',";//清除日期的按钮名称  
		 $json_str .= "closeText:'关闭',";//关闭选择框的按钮名称  
		 $json_str .= "yearSuffix:'年',";//年的后缀  
		 $json_str .= "showMonthAfterYear:true,";//是否把月放在年的后面
		 $json_str .= "currentText:'今天',";
		 $json_str .= "gotoCurrent:true,";
		 $json_str .= "defaultDate:'".date('Y-m-d')."',";//默认日期
		 $json_str .= "monthNames: ['一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月'],";
		 $json_str .= "dayNames: ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'],";
		 $json_str .= "dayNamesShort: ['周日','周一','周二','周三','周四','周五','周六'], ";
		 $json_str .= "dayNamesMin: ['日','一','二','三','四','五','六'],";
		 $json_str .= "onSelect:function(selectedDate){\$table.jqGrid('setGridParam',{postData:{".$options.":selectedDate}}).trigger('reloadGrid');}";//选择日期后执行的操作
  
 **/
function jQgrid_searchBar($type = 'text',$options)
{
	$json_str = '';
	$searchoptions = array(); 
	switch($type)
	{
	   case 'text':
	   
	   break;
	   case 'select':
         $json_str .= " stype:'select',";
		 $temp = array(''=>'');
		 foreach($options as $k=>$v)
		 {
			$temp[$k] = $v;
		 }
		 $searchoptions = array(
		   'value'=>$temp,
		   'defaultValue'=>'',
		 );
		 $json_str .= 'searchoptions:'.json_encode($searchoptions).","; 
	   break;
	   case 'datetime':
	     $json_str .= "searchoptions:{dataInit:function(elem){\$(elem).daterangepicker({"; 
		 $json_str .= "ranges:{";
		 $json_str .= "'".L('TODAY')."':[moment(),moment()],"; 
		 $json_str .= "'".L('YESTERDAY')."':[moment().subtract('days',1),moment().subtract('days',1)],";
		 $json_str .= "'".L('LAST_7_DAYS')."':[moment().subtract('day',6),moment()],";
		 $json_str .= "'".L('LAST_30_DAYS')."':[moment().subtract('days',29),moment()],";
		 $json_str .= "'".L('MONTH')."':[moment().startOf('month'),moment().endOf('month')],";
		 $json_str .= "'".L('LAST_MONTH')."':[moment().subtract('month',1).startOf('month'),moment().subtract('month',1).endOf('month')]";
		 $json_str .= "},";
		 $json_str .= "locale:{";
		 $json_str .= "applyLabel:'".L('CONFIRM')."',";
		 $json_str .= "cancelLabel:'".L('CANCEL')."',";
		 $json_str .= "fromLabel:'".L('FROM')."',";
		 $json_str .= "toLabel:'".L('TO')."',";
		 $json_str .= "weekLabel:'".L('WEEK')."',";
		 $json_str .= "customRangeLabel:'".L('TODAY')."',";
		 $json_str .= "monthNames: ".L('MONTH_LABELS').",";
		 $json_str .= "daysOfWeek: ".L('DOW_LABELS')."";
		 $json_str .= "},";
		 $json_str .= "format:'YYYY-MM-DD'";
		 $json_str .= "},function(){";
		 $json_str .= " var val = this.element.val(); \$table.jqGrid('setGridParam',{postData:{".$options.":val}}).trigger('reloadGrid')";
		 $json_str .= "})}},";
	   break;
		
	}
	return $json_str;
}
/**
 * 输出变量内容,最多输出五个变量
 */
function out($content1=null,$content2=null,$content3=null,$content4=null,$content5=null) {
    header('Content-type: text/html; charset=utf-8');
    $n = func_num_args();
    if($n==0)
    {
        dump('您没有要输出的变量');
        exit;
    }
    $arr=array($content1,$content2,$content3,$content4,$content5);
    dump('---------------------------------------------------------------');
    for($i=0;$i<$n&&$i<4;$i++)
    {
        $key=$i+1;
        if(gettype($arr[$i])=='array')dump($key.'.变量类型：'.gettype($arr[$i]).':'.count($arr[$i]));
        else if(gettype($arr[$i])=='string')dump($key.'.变量类型：'.gettype($arr[$i]).':'.strlen($arr[$i]));
        else dump($key.'.变量类型：'.gettype($arr[$i]));
        if($arr[$i]===null)dump('NULL');
        else if($arr[$i]==='')dump('空字符串');
        else if($arr[$i]===true)dump('true');
        else if($arr[$i]===false)dump('false');
        else if(gettype($arr[$i])=='object'&&get_class($arr[$i])=='Model')dump($arr[$i]->_sql());
        else dump($arr[$i]);
        dump('---------------------------------------------------------------');
    }
    exit;
}


   function arr_add($a,$b){
   	foreach ($a as $k => $v) {
   		if ($b[$k]) {
   		 $arr[$k] = array_merge_recursive($v,$b[$k]);
   		 unset($b[$k]);
   		}else{
   		 $arr[$k] = array_merge_recursive($v);
   		}	
   	}
   	$arr2=$arr+$b;
   	foreach ($arr2 as $k2 => $v2) {
   		$arr3[$k2]=array();
   		foreach ($v2 as $k3 => $v3) {
   			switch ($k3) {
   				case 'c_jietong_max_sec':
   				 if (is_array($v3)) {
   				 	$v4[$k3] = max($v3);
   				 }else{
   				 	$v4[$k3] = $v3;
   				 }
   					
   					break;
   			    case 'c_jietong_min_sec':
   			    if (is_array($v3)) {
   				 	$v4[$k3] = min($v3);
   				 }else{
                   $v4[$k3] = $v3;
   				 }
   					
   					break;
   				
   				default:
   					$v4[$k3] = intval($v3[0])+intval($v3[1]);
   					break;
   			}
   		 	
   		 } 
   		 $arr3[$k2]  = $v4;

   	}
   	return $arr3;
   }
/*------------------------------------------------------ */
//-- 计算并更新当天技能组报表数据
//-- report_date  string 小时  2016-11-21
//-- 2016-11-21
//-- dongjun
/*------------------------------------------------------ */
function reportUpdateQueueData($report_date)
{
	$report_date    = $report_date == '' ? date('Y-m-d') : $report_date;
	$time_from      = strtotime($report_date." 00:00:00");
	$time_to        = strtotime($report_date." 23:59:59");
	$m_report_queue = M('queue_calls');
	$m_cdr          = M('cdr');
	$m_feedback     = M('report_feedback');
	$report_queues  = array();
	//正常的情况
	$data                 = $m_cdr->where("call_time >= %s AND call_time <= %s AND call_type=331 AND ((call_status != 333 AND wait_time >= 6) OR (call_status = 333 AND wait_time >= 20))",$time_from,$time_to)->field("count(cdr_id) as c,SUM(wait_time) as sec,MAX(wait_time) as max_sec,MIN(wait_time) as min_sec,queue_id as Queue,call_status as is_fangqi")->group('Queue,is_fangqi')->select();
	//dump($m_cdr->getlastsql());
	$report_queues_base   = processQueueData($data);
          dump($report_queues_base);
          dump($m_cdr->getlastsql());
	echo "<pre>";
	

	//6秒内放弃数
	//$data                 = $m_report_queue->where("time_begin >= %s AND time_end <= %s AND (is_fangqi = 1 AND HoldTime < 6)",$time_from,$time_to)->field("count(id) as c,SUM(HoldTime) as sec,MIN(HoldTime) as min_sec,MAX(HoldTime) as max_sec,Queue,is_fangqi")->group('Queue')->select();
	$data                 = $m_cdr->where("call_time >= %s AND call_time <= %s AND call_type=331 AND (call_status != 333 AND wait_time < 6)",$time_from,$time_to)->field("count(cdr_id) as c,SUM(wait_time) as sec,MIN(wait_time) as min_sec,MAX(wait_time) as max_sec,queue_id as Queue,call_status as is_fangqi")->group('Queue')->select();
	$report_queues_fq_lt6 = processQueueData($data);
        // dump($report_queues_fq_lt6);
	//20秒内接起率
	$data                 = $m_cdr->where("call_time >= %s AND call_time <= %s AND call_type=331 AND (call_status = 333 AND wait_time < 20)",$time_from,$time_to)->field("count(cdr_id) as c,SUM(wait_time) as sec,MIN(wait_time) as min_sec,MAX(wait_time) as max_sec,queue_id as Queue,call_status as is_fangqi")->group('Queue')->select();
	$report_queues_jt_lt20= processQueueData($data);
     // dump($m_report_queue->getlastsql());
        dump($report_queues_jt_lt20);
	//通话总时长
	$data                 = $m_cdr->where("call_time >= %s AND call_time <= %s AND call_type=331 ",$time_from,$time_to)->field("SUM(billsec) as total_billsec,queue_id as Queue")->group("queue_id")->select();
	$report_total_billsec = processQueueData($data);
	
	//服务评分
	$data                 = $m_feedback->where("add_time >= %s AND add_time <= %s",$time_from,$time_to)->field("SUM(score) as feedback_total_score,count(id) as feedback_count,queue_id as Queue")->group("queue_id")->select();
	$report_feedback      = processQueueData($data);
	
	$m_report_queue       = M('report_queue');
	$type = 1;
        //dump($report_queues_base);
	if(count($report_queues_base) == 0)
	{
		$type = 2;
		$report_queues_base =  $report_queues_fq_lt6;
		if(count($report_queues_base) == 0)
		{
		  $report_queues_base=$report_queues_jt_lt20;
		}
          // dump($report_queues_base);
	}
	$aa=array_keys($report_queues_base);
	$bb=array_keys($report_queues_fq_lt6);
	$cc=array_keys($report_queues_jt_lt20);
	$dd = array_unique(array_merge($aa,$bb,$cc));
        //dump($dd);
        $m_report_queue->where('report_date = "%s"',$report_date)->delete();
	foreach($dd as $queue_id)
	{
          if (!$queue_id) {
			continue;
	  }
	 // $m_report_queue->where('report_date = "%s"',$report_date)->delete();
	  $report_queues = array();  
	  $report_queues['queue_id']            = $queue_id;
	  $report_queues['report_date']         = $report_date;
	  $report_queues['c_all']               = ($report_queues_fq_lt6[$queue_id]['c_all']       + $report_queues_jt_lt20[$queue_id]['c_all']);
	  $report_queues['c_all']               =  $type == 1 ? $report_queues_base[$queue_id]['c_all'] + $report_queues['c_all'] : $report_queues['c_all'];
	  $report_queues['c_total_sec']         = ($report_queues_fq_lt6[$queue_id]['c_total_sec'] + $report_queues_jt_lt20[$queue_id]['c_total_sec']);
	  $report_queues['c_total_sec']         =  $type == 1 ? $report_queues_base[$queue_id]['c_total_sec'] +  $report_queues['c_total_sec'] : $report_queues['c_total_sec'];                                
	  $report_queues['c_fangqi']            = ($report_queues_fq_lt6[$queue_id]['c_fangqi']);
	  $report_queues['c_fangqi']            =  $type == 1 ? $report_queues_base[$queue_id]['c_fangqi']    +   $report_queues['c_fangqi'] :  $report_queues['c_fangqi'] ;
	  $report_queues['c_fangqi_total_sec']  = ($report_queues_fq_lt6[$queue_id]['c_fangqi_total_sec']);
	  $report_queues['c_fangqi_total_sec']  = $type == 1 ? $report_queues_base[$queue_id]['c_fangqi_total_sec'] +  $report_queues['c_fangqi_total_sec'] :  $report_queues['c_fangqi_total_sec'];
	  $report_queues['c_fangqi']  = $report_queues['c_fangqi']?$report_queues['c_fangqi'] :0;
	  $report_queues['c_fangqi_total_sec'] = $report_queues['c_fangqi_total_sec']?$report_queues['c_fangqi_total_sec']:0;
          $report_queues['c_fangqi_min_sec']    = !$report_queues_fq_lt6[$queue_id]['c_fangqi_min_sec'] ?$report_queues_base[$queue_id]['c_fangqi_min_sec'] : $report_queues_fq_lt6[$queue_id]['c_fangqi_min_sec'];
	  $report_queues['c_fangqi_min_sec']    = !$report_queues['c_fangqi_min_sec'] ? 0 : $report_queues['c_fangqi_min_sec'];
	  $report_queues['c_fangqi_max_sec']    = !$report_queues_base[$queue_id]['c_fangqi_max_sec'] ? $report_queues_fq_lt6[$queue_id]['c_fangqi_max_sec'] : $report_queues_base[$queue_id]['c_fangqi_max_sec'];
	  $report_queues['c_fangqi_max_sec']    = !$report_queues['c_fangqi_max_sec'] ? 0 : $report_queues['c_fangqi_max_sec'];
	  $report_queues['c_jietong']           = ($report_queues_jt_lt20[$queue_id]['c_jietong']);
	  $report_queues['c_jietong']           =  $type == 1 ? $report_queues_base[$queue_id]['c_jietong'] + $report_queues['c_jietong'] :  $report_queues['c_jietong'];
	  $report_queues['c_jietong_total_sec'] = ( $report_queues_jt_lt20[$queue_id]['c_jietong_total_sec']);
	  $report_queues['c_jietong_total_sec'] =  $type == 1  ? $report_queues_base[$queue_id]['c_jietong_total_sec'] + $report_queues['c_jietong_total_sec'] : $report_queues['c_jietong_total_sec'];
	  $report_queues['c_jietong_min_sec']   = !$report_queues_jt_lt20[$queue_id]['c_jietong_min_sec'] ? $report_queues_base[$queue_id]['c_jietong_min_sec'] : $report_queues_jt_lt20[$queue_id]['c_jietong_min_sec'];
	  $report_queues['c_jietong_min_sec']   = !$report_queues['c_jietong_min_sec'] ? 0 : $report_queues['c_jietong_min_sec'];
	  $report_queues['c_jietong_max_sec']   = !$report_queues_base[$queue_id]['c_jietong_max_sec'] ? $report_queues_jt_lt20[$queue_id]['c_jietong_max_sec'] : $report_queues_base[$queue_id]['c_jietong_max_sec'];
	  $report_queues['c_jietong_max_sec']   = !$report_queues['c_jietong_max_sec'] ? 0 : $report_queues['c_jietong_max_sec'];
	  $report_queues['c_jietong_lt_20']     = !$report_queues_jt_lt20[$queue_id]['c_all'] ? 0 : $report_queues_jt_lt20[$queue_id]['c_all'];
	  $report_queues['c_fangqi_lt_6']       = !$report_queues_fq_lt6[$queue_id]['c_all']  ? 0 : $report_queues_fq_lt6[$queue_id]['c_all'];
	  $report_queues['total_billsec']       = !$report_total_billsec[$queue_id]['total_billsec'] ? 0  : $report_total_billsec[$queue_id]['total_billsec'];
	  $report_queues['feedback_count']      = !$report_feedback[$queue_id]['feedback_count'] ? 0 : $report_feedback[$queue_id]['feedback_count'];
	  $report_queues['feedback_total_score']= !$report_feedback[$queue_id]['feedback_total_score'] ? 0 : $report_feedback[$queue_id]['feedback_total_score'];
	  //dump($report_queues);
	  $r = $m_report_queue->add($report_queues);
          dump($m_report_queue->getlastsql());
         
	}
 
}
/*------------------------------------------------------ */
//-- 处理技能组报表数据
//--  data array 数据  2016-11-21
//-- 2016-11-21
//-- dongjun
/*------------------------------------------------------ */
function processQueueData($data)
{
	if(!$data)
	{
	  return array();	
	}
	$report_queues = array();
	foreach($data as $info)
	{
		if($info['feedback_total_score'] && $info['feedback_count'])
		{
		  $report_queues[$info['Queue']]['feedback_total_score'] = $info['feedback_total_score'];
		  $report_queues[$info['Queue']]['feedback_count']       = $info['feedback_count'];	
		}
		if($info['total_billsec'])
		{
		  $report_queues[$info['Queue']]['total_billsec'] = $info['total_billsec'];
		  continue;	
		}
		$report_queues[$info['Queue']]['c_all'] += $info['c'];
		$report_queues[$info['Queue']]['c_total_sec'] += $info['sec'];
		if($info['is_fangqi'] != 333)
		{
		 
		  $report_queues[$info['Queue']]['c_fangqi']  += $info['c'];
		  $report_queues[$info['Queue']]['c_fangqi_total_sec'] += $info['sec'];
		  if($info['max_sec'])
		  {
		    $report_queues[$info['Queue']]['c_fangqi_max_sec'] = $info['max_sec'];  
		  }
		  if($info['min_sec'])
		  {
		    $report_queues[$info['Queue']]['c_fangqi_min_sec'] = $info['min_sec'];  
		  }
                  if($info['Queue']==905){ 
                   dump($info['min_sec']);
                   dump($report_queues[$info['Queue']]['c_fangqi_max_sec']);
                   dump($report_queues[$info['Queue']]['c_fangqi_min_sec']);
                  }

		}else{
		  $report_queues[$info['Queue']]['c_jietong'] = $info['c'];
		  $report_queues[$info['Queue']]['c_jietong_total_sec'] = $info['sec'];
		  if($info['max_sec'])
		  {
			$report_queues[$info['Queue']]['c_jietong_max_sec'] = $info['max_sec'];  
		  }
		  if($info['min_sec'])
		  {
			$report_queues[$info['Queue']]['c_jietong_min_sec'] = $info['min_sec'];  
		  }
		}
	}
	return $report_queues;
}

/*------------------------------------------------------ */
//-- 计算并更新当天的各类时长
//-- report_hour  int 小时  0-23
//-- 2016-11-21
//-- dongjun
/*------------------------------------------------------ */
function reportUpdateSecData($report_hour,$report_date="")
{
	 return 1;
  $report_hour = empty($report_hour) ? date('G')     : $report_hour;
  $report_date = ($report_date=="")  ? date('Y-m-d') : $report_date;

  $day_time     = strtotime($report_date);
  $time_from    = $day_time  + $report_hour * 3600;

  $time_to      = $time_from + 3600;
  $current_time = time();
  $m_user_time  = M('user_timer');
  $user_times   = array();
  //不跨时间
  $user_time_1 = $m_user_time->where("start_time >= %s AND end_time <= %s AND end_time != 0",$time_from,$time_to)->field("$report_hour as report_hour,user_id,type,SUM(end_time-start_time) as sec")->group("user_id,type")->select();

  //不跨时间，还没完结，即 end_time = 0的情况,前提条件是小时要小于当前小时才能计算
  if(date("Y-m-d") > $report_date || (date("Y-m-d") == $report_date && date("G") > $report_hour))
  {
	//找到start_time所在的区间
	$user_time_0_1 = $m_user_time->where("start_time > %s AND start_time < %s AND end_time = 0",$time_from,$time_to)->field("$report_hour as report_hour,user_id,type,SUM($time_to - start_time) as sec")->group("user_id,type")->select();
	//如果在更加遥远的过去
	$user_time_0_2 = $m_user_time->where("start_time < %s AND end_time = 0",$time_from)->field("$report_hour as report_hour,user_id,type,3600 as sec")->group("user_id,type")->select();
  }elseif(date("Y-m-d") == $report_date && date("G") == $report_hour){
    //统计是当前时间,timer区间起始点在过去
	$user_time_0_1 = $m_user_time->where("start_time < %s AND end_time = 0",$time_from)->field("$report_hour as report_hour,user_id,type,($current_time - $time_from) as sec")->group("user_id,type")->select();
	//统计当前时间,timer区间起始点在当前时段
	$user_time_0_2 = $m_user_time->where("start_time >= %s AND end_time = 0",$time_from)->field("$report_hour as report_hour,user_id,type,($current_time - start_time) as sec")->group("user_id,type")->select();
  }
  //跨时间，下限
  $user_time_2 = $m_user_time->where("start_time < %s AND end_time > %s AND end_time < %s",$time_from,$time_from,$time_to)->field("$report_hour as report_hour,user_id,type,SUM(end_time - $time_from) as sec")->group("user_id,type")->select();
  
  //跨时间，上限
  $user_time_3 = $m_user_time->where("start_time > %s AND start_time < %s AND end_time > %s",$time_from,$time_to,$time_to)->field("$report_hour as report_hour,user_id,type,SUM($time_to - start_time) as sec")->group("user_id,type")->select();
  //包含时间
  $user_time_4 = $m_user_time->where("start_time < %s AND end_time > %s",$time_from,$time_to)->field("$report_hour as report_hour,user_id,type,$time_to - $time_from as sec")->group("user_id,type")->select();

  if($user_time_1)
  {
	$user_times = array_merge($user_times,$user_time_1);  
  }
  if($user_time_2)
  {
    $user_times = array_merge($user_times,$user_time_2);   
  }
  if($user_time_3)
  {
    $user_times = array_merge($user_times,$user_time_3);   
  }
  if($user_time_4)
  {
    $user_times = array_merge($user_times,$user_time_4);   
  }
  if($user_time_0_1)
  {
    $user_times = array_merge($user_times,$user_time_0_1);   
  }
  if($user_time_0_2)
  {
    $user_times = array_merge($user_times,$user_time_0_2);   
  }
  $result = array();
  foreach($user_times as $info)
  {
	 switch($info['type'])
	 {
		case 1://振铃
		  $result[$info['user_id']]['c_ringing_sec']    += $info['sec'];
		break; 
		case 2://通话
		  $result[$info['user_id']]['c_all_sec']        += $info['sec'];
		break;
		case 3://事后
		  $result[$info['user_id']]['c_afterwards_sec'] += $info['sec'];
		break;
		case 4://暂停
		  $result[$info['user_id']]['c_pause_sec']      += $info['sec'];
		break;
		case 5://就绪
		  $result[$info['user_id']]['c_idle_sec']       += $info['sec'];
		break;
		case 6://在线
		  $result[$info['user_id']]['c_online_sec']     += $info['sec'];
		break;
		case 7://签入
		  $result[$info['user_id']]['c_signin_sec']     += $info['sec'];
 		break;
	 }
  }
  foreach($result as $user_id=>$data)
  {	
  	
	$exists_report = checkExistsReport($report_date,$report_hour,$user_id);

	$repinfo = M("report_base_day")->where("report_date='%s' AND report_hour=%s AND user_id=%s",$report_date,$report_hour,$user_id)->find();
	if ($repinfo) {
		$shihou = ($repinfo["c_in_all"] + $repinfo["c_out_all"])*30;
		//dump($shihou."-".$data["c_afterwards_sec"]);
	  	if ($data["c_afterwards_sec"] > $shihou) {
	  		$data["c_afterwards_sec"] = $shihou;
	  	}
	}

	if(!$exists_report)
    {
	  $data['user_id']     = $user_id;
	  $data['report_hour'] = $report_hour;
	  $data['report_date'] = $report_date;	
	  $data['report_week'] = date("W");
	  $data['add_time']    = time();
	  $r = M("report_base_day")->add($data);
	}else{
	  $r = M("report_base_day")->where("report_date='%s' AND report_hour=%s AND user_id=%s",$report_date,$report_hour,$user_id)->save($data); 
	}
	if($r)
	{
	  $success_count++;	
	}
  }
  return $success_count;
}
/*------------------------------------------------------ */
//-- 检查某天某个小时某个人有没有报表数据
//-- 2015-11-22
//-- dongjun
/*------------------------------------------------------ */
function checkExistsReport($report_date,$report_hour,$user_id)
{
	$count = M('report_base_day')->where("report_date='%s' AND report_hour=%s AND user_id=%s",$report_date,$report_hour,$user_id)->count();
	return !!$count;
}
/*------------------------------------------------------ */
//-- 计算并更新当天的基础数据，不包含各个率
//-- report_hour  int 小时  0-23
//-- 2015-11-22
//-- dongjun
/*------------------------------------------------------ */
function reportUpdateBaseData($report_hour,$report_date="")
{
	$report_hour = empty($report_hour) ? date('G') :$report_hour;
	$report_date = ($report_date=="") ? date('Y-m-d') : $report_date;
	$is_today = ($report_date == date('Y-m-d'))? true : false;

	//删除旧数据
	$m = M('report_base_day');
	$m->where("report_date='%s' AND report_hour=%d",$report_date,$report_hour)->delete();

	$day_time = strtotime($report_date);
	$time_from = $day_time  + $report_hour * 3600;
	$time_to = $time_from + 3600;

	$add_time = time();
	unset($user_data);
	$user_data = reportCountBaseData($time_from,$time_to,$report_date,$report_hour);
	//dump($user_data);
	//exit;
	if(!$user_data) return ;
	$week= intval(date("W",strtotime($report_date)));
	$arr_r = array("error"=>0,"msg"=>'');			
	//循环更新各个人的数据
	foreach($user_data as $list){
		unset($data);
		$data = array(
			"report_date"			=>	$report_date,
			"report_hour"			=>	$report_hour,
			"report_week"			=>	$week,
			"user_id"				=>	$list['user_id'],
			//"d_id"					=>	$list['d_id'],
			"add_time"				=>	$add_time,
			"c_in_all" 				=>	$list['c_in_all'] ? $list['c_in_all'] : 0,  
			"c_in_zhuanzuoxi" 		=>	($list['c_in_zuoxijietong'] ? $list['c_in_zuoxijietong'] : 0)+ ($list['c_in_zuoxiloujie'] ? $list['c_in_zuoxiloujie'] : 0)+ ($list['c_in_paiduifangqi'] ? $list['c_in_paiduifangqi'] : 0), 
			"c_in_zuoxijietong" 	=>	$list['c_in_zuoxijietong'] ? $list['c_in_zuoxijietong'] : 0,  
			"c_in_zuoxiloujie" 		=>	$list['c_in_zuoxiloujie'] ? $list['c_in_zuoxiloujie'] : 0,  
			"c_in_paiduifangqi" 	=>	$list['c_in_paiduifangqi'] ? $list['c_in_paiduifangqi'] : 0,  
			"c_in_ivr" 				=>	$list['c_in_ivr'] ? $list['c_in_ivr'] : 0,  
			"c_in_sec" 				=>	$list['c_in_sec'] ? $list['c_in_sec'] : 0, 
			"c_in_black"            =>  $list['c_in_black'] ? $list['c_in_black'] : 0, 
			"c_out_all" 			=>	$list['c_out_all'] ? $list['c_out_all'] : 0,  
			"c_out_jietong" 		=>	$list['c_out_jietong'] ? $list['c_out_jietong'] : 0,  
			"c_out_sec" 			=>	$list['c_out_sec'] ? $list['c_out_sec'] : 0,  
			"c_all_sec" 			=>	($list['c_in_sec'] ? $list['c_in_sec'] : 0)+($list['c_out_sec'] ? $list['c_out_sec'] : 0),  
		);
		//dump($data);
		if (!$m->add($data))
		{
			$arr_r["error"] ++;
			$arr_r["msg"] .= ";".$m->getlastsql();
		}
	}
	return $arr_r;
}

/*------------------------------------------------------ */
//-- 计算当天，各个坐席的量
//-- 2016-5-21
//-- zhangtuo  于 郴州
/*------------------------------------------------------ */
function reportCountBaseData($time_from,$time_to,$date,$hour)
{
	
	$m = M('Cdr');
   	$ex_where .= " AND call_time >=". $time_from ." AND call_time <".$time_to; ;

	//获得每个坐席的呼入总量
	$arr = $m->query("select user_id,count(*) as c from __TABLE__ where call_type=331 $ex_where group by user_id");
	//dump($m->getlastsql());
	//dump($arr);
	foreach($arr as $v){
		$list[$v["user_id"]]["user_id"]=$v["user_id"];
		$list[$v["user_id"]]["c_in_all"]=$v["c"];
	}
	
	//获得每个坐席的接通量
	$arr = $m->query("select user_id,count(*) as c from __TABLE__ where call_type=331 AND call_status=333 $ex_where group by user_id");
	//dump($m->getlastsql());
	//dump($arr);
	foreach($arr as $v){
		$list[$v["user_id"]]["user_id"]=$v["user_id"];
		$list[$v["user_id"]]["c_in_zuoxijietong"]=$v["c"];
	}

	//获得每个坐席的漏接量
	$arr = $m->query("select user_id,count(*) as c from __TABLE__ where call_type=331 AND call_status=334 $ex_where group by user_id");
	//dump($m->getlastsql());
	//dump($arr);
	foreach($arr as $v){
		$list[$v["user_id"]]["user_id"]=$v["user_id"];
		$list[$v["user_id"]]["c_in_zuoxiloujie"]=$v["c"];
	}

	//获得排队放弃的量
	$arr = $m->query("select user_id,count(*) as c from __TABLE__ where call_type=331 AND call_status=343 $ex_where group by user_id");
	//dump($m->getlastsql());
	//dump($arr);
	foreach($arr as $v){
		$list[$v["user_id"]]["user_id"]=$v["user_id"];
		$list[$v["user_id"]]["c_in_paiduifangqi"]=$v["c"];
	}


	//获得IVR的量
	$arr = $m->query("select user_id,count(*) as c from __TABLE__ where call_type=331 AND call_status=342 $ex_where group by user_id");
	//dump($m->getlastsql());
	//dump($arr);
	foreach($arr as $v){
		$list[$v["user_id"]]["user_id"]=$v["user_id"];
		$list[$v["user_id"]]["c_in_ivr"]=$v["c"];
	}
	//获得黑名单量
	$arr = $m->query("select user_id,count(*) as c,call_type from __TABLE__ where call_status=596 AND call_type=331 $ex_where group by user_id");
	foreach($arr as $v){
		$list[$v["user_id"]]["user_id"]=$v["user_id"];
		$list[$v["user_id"]]["c_in_black"]=$v["c"];
	}
	
	//获得每个坐席的呼入总的通话时长
	$arr = $m->query("select user_id,sum(billsec) as c from __TABLE__ where call_type=331 AND call_status=333 $ex_where group by user_id");
	//dump($m->getlastsql());
	//dump($arr);
	foreach($arr as $v){
		$list[$v["user_id"]]["user_id"]=$v["user_id"];
		$list[$v["user_id"]]["c_in_sec"]=$v["c"];
	}


	//获得每个坐席的呼出总量
	$arr = $m->query("select user_id,count(*) as c from __TABLE__ where call_type=332 $ex_where group by user_id");
	//dump($m->getlastsql());
	//dump($arr);
	foreach($arr as $v){
		$list[$v["user_id"]]["user_id"]=$v["user_id"];
		$list[$v["user_id"]]["c_out_all"]=$v["c"];
	}
	
	//获得每个坐席呼出的接通量
	$arr = $m->query("select user_id,count(*) as c from __TABLE__ where call_type=332 AND call_status=333 $ex_where group by user_id");
	//dump($m->getlastsql());
	//dump($arr);
	foreach($arr as $v){
		$list[$v["user_id"]]["user_id"]=$v["user_id"];
		$list[$v["user_id"]]["c_out_jietong"]=$v["c"];
	}

	//获得每个坐席的呼出总的通话时长
	$arr = $m->query("select user_id,sum(billsec) as c from __TABLE__ where call_type=332 AND call_status=333 $ex_where group by user_id");
	//dump($m->getlastsql());
	//dump($arr);
	foreach($arr as $v){
		$list[$v["user_id"]]["user_id"]=$v["user_id"];
		$list[$v["user_id"]]["c_out_sec"]=$v["c"];
	}
	

	//dump($list);
	return $list;
}

/**
 * 格式化秒
 * @param  $sec int 秒
 * 2012-2-21
 * zhangtuo
 */
function percent_format($i){
	$i = floatval($i);
	if($i){
		return sprintf("%.2f",$i * 100)."%" ;
	}else{
		return "0.00%";
	}
}
/**
 * 格式化秒
 * @param  $sec int 秒
 * 2012-2-21
 * zhangtuo
 */
function sec_format($sec){
	$sec = intval($sec);
	if($sec){
		//return sprintf("%02d",$sec/60).":".sprintf("%02d",$sec%60) ;
		$min = floor($sec/60);
		if($min >= 60){
			return sprintf("%02d",$min/60).":".sprintf("%02d",$min%60).":".sprintf("%02d",$sec%60) ;
		}else{
			return sprintf("%02d",$min).":".sprintf("%02d",$sec%60) ;
		}
	}else{
		return "00:00";
	}
}
//返回坐席报表的全部字段内容
//zhangtuo 2016-5-22
//于郴州
function reportGetAgentBaseField(){
	return array(
			array('field_id'=>0,'name'=>'时间','field'=>'report_date','form_type'=>'datetime'),
			array('field_id'=>1,'name'=>'姓名','field'=>'user_id','form_type'=>'user'),
			array('field_id'=>2,'name'=>'呼入量','field'=>'c_in_all','form_type'=>'int'),
			array('field_id'=>3,'name'=>'呼入转坐席量','field'=>'c_in_zhuanzuoxi','form_type'=>'int'),
			array('field_id'=>4,'name'=>'坐席接通量','field'=>'c_in_zuoxijietong','form_type'=>'int'),
			array('field_id'=>5,'name'=>'坐席漏接量','field'=>'c_in_zuoxiloujie','form_type'=>'int'),
			array('field_id'=>6,'name'=>'坐席接通率','field'=>'r_in_jietong','form_type'=>'int'),
			array('field_id'=>7,'name'=>'排队放弃量','field'=>'c_in_paiduifangqi','form_type'=>'int'),
			array('field_id'=>8,'name'=>'放弃率','field'=>'r_in_paiduifangqi','form_type'=>'int'),
			array('field_id'=>9,'name'=>'IVR量','field'=>'c_in_ivr','form_type'=>'int'),
			array('field_id'=>10,'name'=>'呼入总长','field'=>'c_in_sec','form_type'=>'int'),
			array('field_id'=>11,'name'=>'呼入均长','field'=>'c_ave_in_sec','form_type'=>'int'),
			array('field_id'=>12,'name'=>'外呼量','field'=>'c_out_all','form_type'=>'int'),
			array('field_id'=>13,'name'=>'外呼接通量','field'=>'c_out_jietong','form_type'=>'int'),
			array('field_id'=>14,'name'=>'外呼接通率','field'=>'r_out_jietong','form_type'=>'int'),
			array('field_id'=>15,'name'=>'外呼总长','field'=>'c_out_sec','form_type'=>'int'),
			array('field_id'=>16,'name'=>'外呼均长','field'=>'c_ave_out_sec','form_type'=>'int'),
			array('field_id'=>17,'name'=>'总通话总长','field'=>'c_all_sec','form_type'=>'int'),
			array('field_id'=>18,'name'=>'总通话均长','field'=>'c_ave_sec','form_type'=>'int'),
		);
}


/*------------------------------------------------------ */
//-- 查询agent报表数据
//-- $start_date    string  开始日期 2012-2-12
//-- $end_date      string  截止日期 2012-2-12
//-- $hour          string  截止日期 2012-2-12
//-- $report_type   string  报表类型 hour,day,month
//-- $user_id       string  坐席id  12,16,213
/*------------------------------------------------------ */
function reportGetData($group_by,$start_date,$end_date,$report_hour_from,$report_hour_to,$user_id,$d_id)
{
    //dump($user_id);
    if($start_date ){
        $ex_where .= " AND report_date >= '" . $start_date . "'";
    }
    if($end_date){
        $ex_where .= " AND report_date <= '" . $end_date . "'";
    }
    if($report_hour_from){
        $ex_where .= " AND report_hour >= " . $report_hour_from;
    }
    if($report_hour_to){
        $ex_where .= " AND report_hour < " . $report_hour_to;
    }

    if($user_id ){
        if( strpos($user_id, ',') > 0 ){
            $arr = explode(',',$user_id);
            $ex_where .= " AND user_id ". implode(',',$arr);       
        }else{
            $ex_where .= $user_id ? " AND user_id = '".$user_id."' " : '';       
        }
    }

    $order_by='report_date';
    if($group_by == 'report_hour'){
      $order_by='report_hour';
    }

    if($group_by == 'user_id'){
      $ex_where .= " AND user_id > 0";
    }



  /*************************************************************/
    $m = M('report_base_day');
    $sql = "select report_date,report_hour,report_week,user_id,d_id,sum(c_in_all) as c_in_all,sum(c_in_zhuanzuoxi) as c_in_zhuanzuoxi,sum(c_in_zuoxijietong) as c_in_zuoxijietong,sum(c_in_zuoxiloujie) as c_in_zuoxiloujie,sum(c_in_paiduifangqi) as c_in_paiduifangqi,sum(c_in_ivr) as c_in_ivr,sum(c_in_black) as c_in_black,sum(c_in_sec) as c_in_sec,sum(c_out_all) as c_out_all,sum(c_out_jietong) as c_out_jietong,sum(c_out_sec) as c_out_sec,sum(c_all_sec) as c_all_sec,sum(c_ringing_sec) as c_ringing_sec,sum(IF(c_in_all !=0,c_afterwards_sec,0)) as c_afterwards_sec,sum(c_pause_sec) as c_pause_sec,sum(c_idle_sec) as c_idle_sec,sum(c_signin_sec) as c_signin_sec,sum(c_online_sec) as c_online_sec FROM  __TABLE__ WHERE 1 ".$ex_where."  group by ".$group_by ." order by $order_by ASC ";

    $list = $m->query($sql);
   // F('aaaaa',$m->getlastsql());
    //dump($m->getlastsql());
    //dump($list);
    if(!is_array($list)) return false;

    $all = array(
        'report_date'       => $start_date,
        'report_hour'       => '',
        'report_week'       => '',//$GLOBALS['_LANG']['week'][$week],
        'user_id'           => -1,
        'd_id'              => '',
        'c_in_all'          => '',
        'c_in_zhuanzuoxi'   => '',
        'c_in_zuoxijietong'  => '',
        'c_in_zuoxiloujie'  => '',
        'c_in_paiduifangqi' => '',
        'c_in_ivr'          => '',
		'c_in_black'        => '',
        'c_in_sec'          => '',
        'c_out_all'         => '',
        'c_out_jietong'         => '',
        'r_out_jietong'         => '',
        'c_out_sec'         => '',
        'c_all_sec'         => '',
        'c_ringing_sec'     => '',
        'c_afterwards_sec'  => '',
        'c_pause_sec'       => '',
        'c_idle_sec'        => '',
		'c_sigin_sec'       => '',
		'c_online_sec'      => '',
    ); 

 	$tmp = D('UserView')->field('user_id,account,name,department_name')->select();
	$user_list = array();
	foreach($tmp as $v){
	  	$user_list[$v['user_id']] =$v;
	}   
    $count = count($list);
    for($i = 0 ; $i< $count ;$i++){
    	if($list[$i]['user_id'] >0){
    		$list[$i]['account']         = $user_list[$list[$i]['user_id']]['account'];
    		$list[$i]['name']            = $user_list[$list[$i]['user_id']]['name'];
    		$list[$i]['department_name'] = L($user_list[$list[$i]['user_id']]['department_name']);
    	}
        //统计总数
        $all['c_in_all']          += $list[$i]['c_in_all'];
        $all['c_in_zhuanzuoxi']   += $list[$i]['c_in_zhuanzuoxi'];
        $all['c_in_zuoxijietong'] += $list[$i]['c_in_zuoxijietong'];
        $all['c_in_zuoxiloujie']  += $list[$i]['c_in_zuoxiloujie'];
        $all['c_in_paiduifangqi'] += $list[$i]['c_in_paiduifangqi'];
        $all['c_in_ivr']          += $list[$i]['c_in_ivr'];
		$all['c_in_black']        += $list[$i]['c_in_black'];
        $all['c_in_sec']          += $list[$i]['c_in_sec'];
        $all['c_out_all']         += $list[$i]['c_out_all'];
        $all['c_out_jietong']         += $list[$i]['c_out_jietong'];
        $all['c_out_sec']         += $list[$i]['c_out_sec'];
        $all['c_all_sec']         += $list[$i]['c_all_sec'];
        $all['c_ringing_sec']     += $list[$i]['c_ringing_sec'];
        $all['c_afterwards_sec']  += $list[$i]['c_afterwards_sec'];
        $all['c_pause_sec']       += $list[$i]['c_pause_sec'];
        $all['c_idle_sec']        += $list[$i]['c_idle_sec'];
		$all['c_sigin_sec']       += $list[$i]['c_sigin_sec'];
		$all['c_online_sec']      += $list[$i]['c_online_sec'];
    }
    $all = array(0=>$all);
    $list = reportCountRate($list);
    $all  = reportCountRate($all);
    //dump($list);
    return array(
        "count" => $count,
        'list'  => $list,
        'all'   => $all[0],
    );
}

//生成各种率
//zhangtuo 2016-5-21 于郴州
function reportCountRate($list)
{
	
	for($i = 0 ; $i<count($list) ;$i++){
			//呼入平均通话时长  =  呼入总通话时长/坐席接通量
			$list[$i]["c_ave_in_sec"]	=	( $list[$i]["c_in_zuoxijietong"] > 0 && $list[$i]["c_in_sec"] > 0 )?round($list[$i]["c_in_sec"] / $list[$i]["c_in_zuoxijietong"]) : 0;
			
			// 呼入坐席接通率  =  呼入坐席接通量/转坐席总量
			$list[$i]["r_in_jietong"] 		=	( $list[$i]["c_in_zhuanzuoxi"] > 0 && $list[$i]["c_in_zuoxijietong"] > 0 )?round($list[$i]["c_in_zuoxijietong"] /$list[$i]["c_in_zhuanzuoxi"],4) : 0;
           
            //排队放弃率 = 放弃量/转坐席量
			$list[$i]['r_in_paiduifangqi'] = ($list[$i]["c_in_paiduifangqi"] > 0 && $list[$i]["c_in_zhuanzuoxi"] > 0 )?round($list[$i]["c_in_paiduifangqi"] /$list[$i]["c_in_zhuanzuoxi"],4) : 0;
		
			//呼出平均通话时长  =  呼出总通话时长/呼出坐席接通量
			$list[$i]["c_ave_out_sec"]	=	( $list[$i]["c_out_jietong"] > 0 && $list[$i]["c_out_sec"] > 0 )?round($list[$i]["c_out_sec"] / $list[$i]["c_out_jietong"]) : 0;
			
			// 呼出坐席接通率  =  呼出坐席接通量/呼出总量
			$list[$i]["r_out_jietong"] 		=	( $list[$i]["c_out_all"] > 0 && $list[$i]["c_out_jietong"] > 0 )?round($list[$i]["c_out_jietong"] /$list[$i]["c_out_all"],4) : 0;
           

			//格式化数据
			$list[$i]['r_in_jietong_format'] 		= percent_format($list[$i]['r_in_jietong']);
			$list[$i]['r_in_paiduifangqi_format'] 	= percent_format($list[$i]['r_in_paiduifangqi']);
			$list[$i]['r_out_jietong_format'] 		= percent_format($list[$i]['r_out_jietong']);
			$list[$i]['c_out_sec_format'] 		= sec_format($list[$i]['c_out_sec']);
			$list[$i]['c_in_sec_format'] 		= sec_format($list[$i]['c_in_sec']);
			$list[$i]['c_ave_out_sec_format'] 		= sec_format($list[$i]['c_ave_out_sec']);
			$list[$i]['c_ave_in_sec_format'] 		= sec_format($list[$i]['c_ave_in_sec']);
			$list[$i]['c_all_sec_format'] 		= sec_format($list[$i]['c_all_sec']);
			$list[$i]['c_ringing_sec_format'] 		= sec_format($list[$i]['c_ringing_sec']);
			$list[$i]['c_afterwards_sec_format'] 		= sec_format($list[$i]['c_afterwards_sec']);
			$list[$i]['c_pause_sec_format'] 		= sec_format($list[$i]['c_pause_sec']);
			$list[$i]['c_idle_sec_format'] 		= sec_format($list[$i]['c_idle_sec']);
			$list[$i]['c_online_sec_format']    = sec_format($list[$i]['c_online_sec']);
			$list[$i]['c_signin_sec_format']    = sec_format($list[$i]['c_signin_sec']);
			$next_hour 						    = $list[$i]['report_hour'] + 1;
			$list[$i]['report_hour_format']     = $list[$i]['report_hour'] ."点-". $next_hour ."点";
			$list[$i]['report_week_format']     = "第 ". $list[$i]['report_week'] ." 周";
	}
	return $list;
	
}

/*------------------------------------------------------ */
//-- 查询满意度报表数据
//-- $start_date    int    开始日期 时间戳
//-- $end_date      int    截止日期 时间戳
//-- $user_id       int    坐席id
//-- $d_id          int    部门id
/*------------------------------------------------------ */
function GetFeedbackData($start_date,$end_date,$user_id,$d_id)
{
    $ex_where = '1';
    if($start_date ){
        $ex_where .= " AND add_time >= " . $start_date ;
    }
    if($end_date){
        $ex_where .= " AND add_time <= " .( $end_date + 86400);
    }
    session('satis_where',$ex_where);
    if($d_id){
    	$user_list = M('user')->where('status=1 AND department_id='.$d_id)->getField('user_id',true);
    	$user_ids = implode(',',$user_list);
    	$ex_where .= ' AND user_id in('.$user_ids.')';
    }
    $m = M('report_feedback');
    $list = $m->field('user_id,score,count(id) as count')->where($ex_where)->group('user_id,score')->order('user_id')->select();

    //合并数组，用user_id作为键
    $arr = array();
    foreach ( $list as $k => $v) {
    	$arr[$v['user_id']][$v['score']] = $v['count'];
    }
    //填补数组，如果不存在评价，就补0，不存在非常满意补0 ...
    foreach ($arr as $k1 => $v1) {
		for ($i=0; $i < 5; $i++) { 
	    	if($v1[$i]){
				$v1[$i] = $v1[$i];
		    }else{
	            $v1[$i] = 0;
		    }
		}
	    ksort($v1);
	    $arr[$k1]=$v1;  
    }
    //解析数组，转化格式
    foreach ($arr as $k2 => $v2) {
    	$total_comment = 0;
    	$success_comment = 0;
    	$fail_count = 0;
    	foreach ($v2 as $key => $val) {
    		if($val){
    		$total_comment +=$val;
    		}

    		if($key){
	    		if($val){
	    		 $success_comment +=$val;	
	    		}
    		}
    	}
    	$arr_user_list= getUserList();
    	$arr_dep_list= getDepList();
    	$fail_count =$total_comment-$success_comment; 
    	$arr1[]=array(
    		'user_id1'         		 	 => $k2,
	        'user_id'         		 	 => $arr_user_list[$k2]['name'],
	        'd_id'                       => $arr_dep_list[$arr_user_list[$k2]['department_id']]['name'],
	        'total_comment'          	 => $total_comment,
	        'success_comment'  			 => $success_comment,
	        'fail_count' 				 => $fail_count,
	        'leve_1' 					 => $v2[1],
	        'leve_2' 					 => $v2[2],
	        'leve_3'         			 => $v2[3],
	        'leve_4'        			 => $v2[4],
        ); 
    }

    if(!is_array($list)) return false;

    $list = reportSatisfactionRate($arr1);
    return array(
        "count" => $count,
        'list'  => $list,
    );
}

//生成满意度报表的各种率
function reportSatisfactionRate($list)
{  
	$count = count($list);
	for($i = 0 ; $i<$count ;$i++){  
		//用户参与率 = 评定总数 / 接通量
		$list[$i]["take_rate"]	=	( $list[$i]["success_comment"] > 0 && $list[$i]["total_comment"] > 0 )?round($list[$i]["success_comment"] / $list[$i]["total_comment"],4) : 0;
		
		// 满意率 = 非常满意+满意/评定成功数
		$list[$i]["satisfaction_rate"] 		=	( $list[$i]["leve_2"] > 0 || $list[$i]["leve_1"] > 0 && $list[$i]["success_comment"] > 0 )?round(($list[$i]["leve_1"]+$list[$i]["leve_2"]) /$list[$i]["success_comment"],4) : 0;
       
        //一般率 = 一般/评定成功数
		$list[$i]['general_rate'] = ($list[$i]["leve_3"] > 0 && $list[$i]["success_comment"] > 0 )?round($list[$i]["leve_3"] /$list[$i]["success_comment"],4) : 0;
	
		//不满意/评定成功数
		$list[$i]["pique_rate"]	=	( $list[$i]["leve_4"] > 0 && $list[$i]["success_comment"] > 0 )?round($list[$i]["leve_4"] / $list[$i]["success_comment"],4) : 0;
		
		//格式化数据
		$list[$i]['take_rate_format'] 		    = percent_format($list[$i]['take_rate']);
		$list[$i]['satisfaction_rate_format'] 	= percent_format($list[$i]['satisfaction_rate']);
		$list[$i]['general_rate_format'] 		= percent_format($list[$i]['general_rate']);
		$list[$i]['pique_rate_format'] 		    = percent_format($list[$i]['pique_rate']);
	}
	return $list;
}

/*------------------------------------------------------ */
//-- 查询技能组报表数据
//-- $start_date    string  开始日期 2012-2-12
//-- $end_date      string  截止日期 2012-2-12
/*------------------------------------------------------ */
function GetQueueData($start_date,$end_date)
{
    if($start_date ){
        $ex_where .= " AND report_date >= '" . $start_date ."'";
    }
    if($end_date){
        $ex_where .= " AND report_date <='" . $end_date ."'";
    }

  /*************************************************************/
    $m = M('report_queue');
   // $sql = "select queue_id,report_date,sum(c_all) as c_all,sum(c_jietong) as c_jietong,sum(c_fangqi) as c_fangqi,sum(c_jietong_lt_20) as c_jietong_lt_20,sum(c_fangqi_lt_6) as c_fangqi_lt_6,sum(c_jietong_total_sec) as c_jietong_total_sec,sum(c_jietong_max_sec) as c_jietong_max_sec,sum(c_jietong_min_sec) as c_jietong_min_sec,sum(c_fangqi_total_sec) as c_fangqi_total_sec,sum(c_fangqi_max_sec) as c_fangqi_max_sec,sum(c_fangqi_min_sec) as c_fangqi_min_sec,sum(total_billsec) as total_billsec,sum(feedback_total_score) as feedback_total_score,sum(feedback_count) as feedback_count FROM  __TABLE__ WHERE 1 ".$ex_where." group by queue_id order by report_date ASC ";
    $sql = "select queue_id,report_date,sum(c_all) as c_all,sum(c_jietong) as c_jietong,sum(c_fangqi) as c_fangqi,sum(c_jietong_lt_20) as c_jietong_lt_20,sum(c_fangqi_lt_6) as c_fangqi_lt_6,sum(c_jietong_total_sec) as c_jietong_total_sec,max(c_jietong_max_sec) as c_jietong_max_sec,min(c_jietong_min_sec) as c_jietong_min_sec,sum(c_fangqi_total_sec) as c_fangqi_total_sec,max(c_fangqi_max_sec) as c_fangqi_max_sec,MIN(c_fangqi_min_sec) as c_fangqi_min_sec,sum(total_billsec) as total_billsec,sum(feedback_total_score) as feedback_total_score,sum(feedback_count) as feedback_count FROM  __TABLE__ WHERE 1 ".$ex_where." group by queue_id order by report_date ASC ";
    $list = $m->query($sql);
    F('queuesql',$sql);
    if(!is_array($list)) return false;

    $all = array(
    	'queue_id'          => '',
        'report_date'       => $start_date,
        'c_all'             => '',
        'c_jietong'  	    => '',
        'c_fangqi'		    => '',
        'c_jietong_lt_20'   => '',
        'c_fangqi_lt_6' 	=> '',
        'c_jietong_ave_sec' => '',
        'c_jietong_max_sec' => '',
        'c_jietong_min_sec' => '',
        'c_fangqi_ave_sec'  => '',
        'c_fangqi_max_sec'  => '',
        'c_fangqi_min_sec'  => '',
        'c_ave_billsec'     => '',
    ); 

    $count = count($list);
    $queue_list = getQueuesList();
    foreach ($queue_list as $k => $v) {
    	$queue_list[$v['queue_id']] = $v;
    }
    for($i = 0 ; $i< $count ;$i++){
    	if($list[$i]['queue_id'] > 0){
    		$list[$i]['queue_name'] = $queue_list[$list[$i]['queue_id']]['queue_id'].L($queue_list[$list[$i]['queue_id']]['queue_note']);
    	}
        //统计总数
        $all['c_all'] += $list[$i]['c_all'];
        //$all['c_all'] +=$list[$i]['c_jietong']+$list[$i]['c_fangqi'];
        $all['c_jietong']   += $list[$i]['c_jietong'];
        $all['c_fangqi'] += $list[$i]['c_fangqi'];
        $all['c_jietong_lt_20']   += $list[$i]['c_jietong_lt_20'];
        $all['c_fangqi_lt_6'] += $list[$i]['c_fangqi_lt_6'];
       // $all['c_jietong_ave_sec']  += $list[$i]['c_jietong_ave_sec'];
        $all['c_jietong_total_sec']  +=$list[$i]["c_jietong_total_sec"];
        $all['c_jietong_max_sec'] += $list[$i]['c_jietong_max_sec'];
        $all['c_jietong_min_sec']  += $list[$i]['c_jietong_min_sec'];
        $all['c_fangqi_ave_sec']  += $list[$i]['c_fangqi_ave_sec'];
        $all['c_fangqi_max_sec']  += $list[$i]['c_fangqi_max_sec'];
        $all['c_fangqi_min_sec']  += $list[$i]['c_fangqi_min_sec'];
        $all['c_fangqi_total_sec']  += $list[$i]['c_fangqi_total_sec'];
        $all['total_billsec']  += $list[$i]['total_billsec'];
        $all['c_ave_billsec']  += $list[$i]['c_ave_billsec'];
    }
    $all = array(0=>$all);
    $list = reportQueueRate($list);
    $all  = reportQueueRate($all);
    //dump($list);
    return array(
        "count" => $count,
        'list'  => $list,
        'all'   => $all[0],
    );
}

//生成技能组报表的各种率
function reportQueueRate($list)
{  
	for($i = 0 ; $i<count($list) ;$i++){
			//排队接通率 = 排队接通数 / 排队总数
			$list[$i]["r_jietong"] = ( $list[$i]["c_jietong"] > 0 && $list[$i]["c_all"] > 0 )?round($list[$i]["c_jietong"] / $list[$i]["c_all"],4) : 0;
			
			//接通排队均长 = 接通排队总长 / 排队接通数
			$list[$i]["c_jietong_ave_sec"] = ( $list[$i]["c_jietong_total_sec"] > 0 && $list[$i]["c_jietong"] > 0 )?round($list[$i]["c_jietong_total_sec"] / $list[$i]["c_jietong"]) : 0;
           
            //放弃排队均长 = 放弃排队总长 / 排队放弃数
			$list[$i]['c_fangqi_ave_sec'] = ($list[$i]["c_fangqi_total_sec"] > 0 && $list[$i]["c_fangqi"] > 0 )?round($list[$i]["c_fangqi_total_sec"] / $list[$i]["c_fangqi"]) : 0;
		
			//平均通话时长 = 接通总长 / 排队接通数
			$list[$i]["c_ave_billsec"] = ( $list[$i]["total_billsec"] > 0 && $list[$i]["c_jietong"] > 0 )?round($list[$i]["total_billsec"] / $list[$i]["c_jietong"]) : 0;
			
			//平均服务水平 = 服务总分 / 评分个数
			//$list[$i]["r_feedback"] = ( $list[$i]["feedback_total_score"] > 0 && $list[$i]["feedback_count"] > 0 )?round($list[$i]["feedback_total_score"] / $list[$i]["feedback_count"],1) : 0;
			//平均服务水平 = 20S内接起数/排队总数(不包含非工昨日排队数)
			$list[$i]["r_feedback"] = ( $list[$i]['c_jietong_lt_20'] > 0 && $list[$i]["c_all"] > 0 )?round( $list[$i]['c_jietong_lt_20'] / $list[$i]["c_all"],4) : 0;

			//不包含6秒放弃数接通率 = 排队接通数 + 6秒放弃数 / 排队总数
			$list[$i]["r_jietong_not_6"] = ( $list[$i]["c_jietong"] > 0 || $list[$i]["c_fangqi_lt_6"] > 0 && $list[$i]["c_all"] > 0 )?round(($list[$i]["c_jietong"] + $list[$i]["c_fangqi_lt_6"]) / $list[$i]["c_all"],4) : 0;

			//格式化数据
			$list[$i]['r_jietong_format'] 			= percent_format($list[$i]['r_jietong']);
			$list[$i]['r_feedback_format'] 			= percent_format($list[$i]['r_feedback']);
			$list[$i]['r_jietong_not_6_format'] 	= percent_format($list[$i]['r_jietong_not_6']);
			$list[$i]['c_all_format'] 				= sec_format($list[$i]['c_all']);
			$list[$i]['c_jietong_format'] 			= sec_format($list[$i]['c_jietong']);
			$list[$i]['c_fangqi_format'] 			= sec_format($list[$i]['c_fangqi']);
			$list[$i]['c_jietong_lt_20_format'] 	= sec_format($list[$i]['c_jietong_lt_20']);
			$list[$i]['c_fangqi_lt_6_format'] 		= sec_format($list[$i]['c_fangqi_lt_6']);
			$list[$i]['c_jietong_ave_sec_format'] 	= sec_format($list[$i]['c_jietong_ave_sec']);
			$list[$i]['c_jietong_max_sec_format'] 	= sec_format($list[$i]['c_jietong_max_sec']);
			$list[$i]['c_jietong_min_sec_format'] 	= sec_format($list[$i]['c_jietong_min_sec']);
			$list[$i]['c_fangqi_ave_sec_format'] 	= sec_format($list[$i]['c_fangqi_ave_sec']);
			$list[$i]['c_fangqi_max_sec_format'] 	= sec_format($list[$i]['c_fangqi_max_sec']);
			$list[$i]['c_fangqi_min_sec_format'] 	= sec_format($list[$i]['c_fangqi_min_sec']);
			$list[$i]['c_ave_billsec_format'] 		= sec_format($list[$i]['c_ave_billsec']);
	}
	return $list;
}

//生成柱状图需要的数据
//zhangtuo 2016-5-22
//于郴州
function reportGetChartData($title,$data,$x)
{
	//dump($title);
	//dump($data);
	if(!is_array($title) ||!is_array($data) ||$x =="") return false;
	$count = count($data);
	$arr_data = array();
	$arr_x = array();
	for($i = 0 ;$i<$count;$i++){
		$arr_x[] = $data[$i][$x];
		foreach($title as $k=>$v){
			$value = strpos($k,'_format')  >0  ?$data[$i][str_replace('_format','',$k)] : $data[$i][$k];
			$arr_data[$k][] = $value;
		}
	}
	return array('x_list'=>$arr_x,'data_list'=>$arr_data);
} 

function reportGetFalshXml2($title,$data,$x)
{
	if(!is_array($title) ||!is_array($data) ||$x =="") return false;
	$count = count($data);
	for($i = 0 ;$i<$count;$i++){
	foreach($title as $k=>$v){
	if($i == 0){
	switch($v[1]){
	case '个':
	$numberScaleValue = "1";
	$numberScaleUnit = "个";
	break;
	case '通':
	$numberScaleValue = "1";
	$numberScaleUnit = "通";
	break;
	case '%':
	$numberScaleValue = "0.01";
	$numberScaleUnit = "％";
	break;
	case '秒':
	$numberScaleValue = "1,60,60,24,7";
	$numberScaleUnit = "秒,分钟,小时,天,星期";
	break;
	default :
	$numberScaleValue = "1";
	$numberScaleUnit = "个";
	break;
	}
	$xml[$k] = "<graph caption=\'".$v['0']."\' xAxisName=\'\' yAxisName=\'\' formatNumberScale=\'1\' numberPrefix=\'\' numberSuffix=\'\'  numberScaleValue=\'".$numberScaleValue ."\' numberScaleUnit=\'".$numberScaleUnit."\'  showNames=\'1\'  showValues=\'1\' outCnvBaseFontSize=\'13\' baseFontSize=\'12\' captionFontSize=\'12\'>";
	}
	$value = strpos($k,'_format')  >0  ?$data[$i][str_replace('_format','',$k)] : $data[$i][$k];
	$xml[$k] .= "<set name=\'".$data[$i][$x]."\' value=\'".$value."\' colo=\'AFD8F8\' />";
	if($i == $count -1){
	$xml[$k] .= "</graph>";
	}
	}
	}
	return $xml;
} 


//报表数据导出excel
//zhangtuo 2016-5-22
//于郴州
function reportDB2excel($filename,$title,$data)
{
		C('OUTPUT_ENCODE', false);
        import("ORG.PHPExcel.PHPExcel");
		$objPHPExcel = new PHPExcel();    
		$objProps = $objPHPExcel->getProperties();    
		$objProps->setCreator("smartcrm");
		$objProps->setLastModifiedBy("smartcrm");    
		$objProps->setTitle("smartcrm");    
		$objProps->setSubject("smartcrm");    
		$objProps->setDescription("smartcrm");    
		$objProps->setKeywords("smartcrm");    
		$objProps->setCategory("smartcrm");
		$objPHPExcel->setActiveSheetIndex(0);     
		$objActSheet = $objPHPExcel->getActiveSheet(); 
		   
		$objActSheet->setTitle('Sheet1');
        $row = 1; //行坐标
        $col = "A"; //列坐标
		foreach($title as $k=>$v){
			$objActSheet->setCellValue($col.$row, $v[0]);
            $col ++;
            //dump($col.$row);
		}		
		foreach($data as $d){
			$row ++;
			$i = 0;
			$col = "A"; //列坐标
			foreach($title as $key=>$v){
				if($key !="report_hour_format" && $key !="report_week_format" && strpos($key,'_format')){
					$value =  $d[str_replace('_format','',$key)] ;
				}else{
					$value =   $d[$key];
				}
				
				$objActSheet->setCellValue($col.$row, $value);
				$col++;
			}
		}
		ob_end_clean();
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        header("Content-Type: application/vnd.ms-excel;");
        header("Content-Disposition:attachment;filename=".$filename.".xls");
        header("Pragma:no-cache");
        header("Expires:0");
        $objWriter->save('php://output'); 
}
    /**
     * 转换成二进制数据
     * bin2hex() 
     * 2016-7-11
     * 葛满堂
     */
	function fileBin2hex($pic){	    	   
        $file = file_get_contents($pic);
        return bin2hex($file);
	}

	/**
     * 读取文件信息
     * $user_id  用户id  必填
     * 2016-7-12
     * 葛满堂
     */
	function userFile($user_id){
        header("Content-Type:image/jpg");
        //读取user表中对应的accessory_id
        $accessory_id = M('User')->where("user_id=%d",$user_id)->getField('accessory_id');
        $csk = M('Accessory')->where("accessory_id=%d",$accessory_id)->getField('csk');
		//return pack('H*',$csk);
		return $csk;
	}
	/*知识库读取缩略图图片 葛满堂*/
    function faqImg($faq_file){
        header("Content-Type:image/jpg");      
        $csk = M('Accessory')->where("type = 'faq'")->getField('csk',true);
        //out($csk);
        $csk_list =array();
        foreach($csk as $k=>$v){
               $csk_list[] = pack('H*',$v);
               //out($csk_list[]);           
        }         
       return $csk_list[$faq_file];	
	} 
	/*知识库读取原图图片 葛满堂*/
	function artImg($faq_file){
		header("Content-Type:image/jpg");
		$accessory_csk = M('Accessory')->where("type = 'faq'")->getField('accessory_id,faqimg',true);
		//out($accessory_csk);
		$csk_list =array();
        foreach($accessory_csk as $k=>$v){
               $csk_list[$k] = pack('H*',$v);
               //out(pack('H*',$v));                       
        }  
		return $csk_list[$faq_file];
	}
    /**
     * 检查文件是否存在
     * @return  $url string 
     * 2012-6-6
     * zhangtuo
     */
    function check_remote_file_exists($url) 
     { 
         $curl = curl_init($url);
         // 不取回数据 
         curl_setopt($curl, CURLOPT_NOBODY, true); 
         // 发送请求 
         $result = curl_exec($curl);
         $found = false; 
         // 如果请求没有发送失败 
         if ($result !== false) { 


         // 再检查http响应码是否为200 
         	$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
         	if ($statusCode == 200) { 
         		$found = true; 
         	} 
         } 
         curl_close($curl); 
         return $found; 
     }
     /*
     *文件大小转换
     */
     function format_bytes($size, $delimiter = '') {
            $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
            for ($i = 0; $size >= 1024 && $i < 6; $i++) $size /= 1024;
            return round($size, 2) . $delimiter . $units[$i];
        }
		//字符串转换，不能用gb2312,因为生僻字会出错，例如"玥翀"
	  function utf2gb($str){
		if($str){
			//return mb_convert_encoding($str,"gb2312","UTF-8");
			//return "\t".iconv("UTF-8","gbk//TRANSLIT",$str)."";
			return iconv("UTF-8","gbk//TRANSLIT",$str);
		}else{
			return "";
		}
	  }

	/**
	 *  author   : wangchao
	 *  function : 获取客户分组array，默认key是customer_id
	 *  date     : 2016-07-08
	 */
	function getCustomerList($which_field_as_index ="customer_id") {
		$list = M('Customer')->field('customer_id,is_deleted,name')->select(); 
		$arr = array();
		foreach($list as $v){
			if($v['is_deleted'] == 1){
				$v['name'] = $v['name'].'(已删)';
			}
			$arr[$v[$which_field_as_index]] = $v;
		}
		//dump($arr);
		return $arr;
	}

	/**
	 *  author   : wangchao
	 *  function : 检测是否是手机号，返回手机号对应号码段的归属地、运营商、区号等信息
	 *  param 	 : $phone手机号
	 *  date     : 2016-10-08
	 */
	/*function getNumlibrary($phone){
		//解析字符串，得到没有前缀的手机号
		$phoneInfo = getPhoneArray($phone);
		if(checkPhone($phone)){
			//截取号段(前7位)
			$mobile = substr($phoneInfo['phone'], 0, 7);
			//查询号段所属的省份、城市、运营商、区号，并返回数组
			$numlibrarys = M('Numlibrary')->where("Mobile = '%s'",$mobile)->field('Province,City,Corp')->find();
			if($numlibrarys['Province'] == $numlibrarys['City']){
				return array_unique($numlibrarys);
			}else{
				return array('Province'=>$numlibrarys['Province'].$numlibrarys['City'],"Corp"=>$numlibrarys['Corp']);
			}
		}
	}*/
		function getNumlibrary($phone){
			//解析字符串，得到没有前缀的手机号
			//dump(1111);
			$phoneInfo = getPhoneArray($phone);
			//dump($phoneInfo['phone']);
			if(checkPhone($phone)){
				
				//判断区分手机  固话
				if ($phoneInfo['type'] && $phoneInfo['type']=='guhua'){

					if (strlen($phoneInfo['phone'])!=7) {
		
				    $mobile ='0'.substr($phoneInfo['phone'],0,-7);
				    //查询号段所属的省份、城市 并返回数组
				    //$numlibrary = M('TelNumlibrary')->where("Mobile = '%s'",$mobile)->field('Province,City')->find();
				     $numlibrary = M('Numlibrary')->where("AreaCode = '%s'",$mobile)->field('Province,City')->find();
		            if (empty($numlibrary)) {
		            	$mobile ='0'.substr($phoneInfo['phone'],0,-8);
				       //查询号段所属的省份、城市 并返回数组
				       $numlibrary = M('Numlibrary')->where("AreaCode = '%s'",$mobile)->field('Province,City')->find();
					 }
					 if($numlibrary['Province'] == $numlibrary['City']){
					 	return array_unique($numlibrary);
					 }else{
					 	return array('Province'=>$numlibrary['Province'].' '.$numlibrary['City'],'Corp'=>'');
					 }
				    }else{
	                    return array('Province'=>'湖北省 武汉市','Corp'=>'');
				    }
				   }else{
	                //截取号段(前7位)
	                $mobile = substr($phoneInfo['phone'], 0, 7);
	                //查询号段所属的省份、城市、运营商、区号，并返回数组
	                $numlibrarys = M('Numlibrary')->where("Mobile = '%s'",$mobile)->field('Province,City,Corp')->find();
	                if($numlibrarys['Province'] == $numlibrarys['City']){
	                	return array_unique($numlibrarys);
	                }else{
	                	return array('Province'=>$numlibrarys['Province'].' '.$numlibrarys['City'],"Corp"=>L($numlibrarys['Corp']));
	                }
				   }
			
			}
		}

			/**
			 *  author   : whh
			 *  function : 获取客户相关 归属地
			 *  param 	 : $id传入 customer_id
			 *  date     : 2017-05-08
			 */
			function getCidlibrary($id){
			    $customer_phone     = M('customer')->field('name,phone')->where('customer_id=%d',$id)->find();
		        $phone_view = M('Contacts')->where('customer_id =%d',$id)->order('order_id')->getField('phone,phone_prefix');
		        if (is_numeric($customer_phone['name'])) {
		        	$phone = $customer_phone['name'];
		        } 
		      
		        $arr_gongdan_area   = getNumlibrary($phone_view[$phone].$phone);
		       // dump( $customer_phone);
		       // dump( $phone_view);
		       // dump( $phone);
		        return explode(' ',$arr_gongdan_area['Province']);
			}
		

	/**
	 *  author   : whh
	 *  function : 获取top10排行数据
	 *  date     : 2016-10-25
	 */
	function reportGsdGetData($where){
         $cdr = M('cdr');
         $result_hr = $cdr->field('call_city,count(cdr_id) as c')->where('call_type = 331 '.$where)->group('call_city')->order('c desc')->limit(11)->select();
         $result_hc = $cdr->field('call_city,count(cdr_id) as c' )->where('call_type = 332 '.$where)->group('call_city')->order('c desc')->limit(11)->select();
         //dump($cdr->getlastsql());

         $result1_hr = $cdr->field('call_city,sum(billsec) as s')->where('call_type = 331 '.$where)->group('call_city')->order('s desc')->limit(11)->select();
         $result1_hc = $cdr->field('call_city,sum(billsec) as s')->where('call_type = 332 '.$where)->group('call_city')->order('s desc')->limit(11)->select();
         //dump($cdr->getlastsql());
        // exit;
        /* $result_hr = $cdr->field('city,count(cdr_id),call_type')->where('1 '.$where)->group('city,call_type')->order('count(cdr_id) desc')->limit(22)->select();
         out($result_hr,$cdr->getlastsql());*/
        //out($result_hr,$cdr->getlastsql());
         return  array(  
		    	          'result_hr' => $result_hr,
		    	          'result_hc' => $result_hc,
		    	          'result1_hr' => $result1_hr,
		    	          'result1_hc' => $result1_hc,
		    	          );
	}

	/**
	 *  author   : whh
	 *  function : 匹配转换柱形图格式的通话数据
	 *  date     : 2016-10-25
	 */
	function reportGsdChartData($ydata,$data_type,$y_date,$count_type){
       if(deep_in_array(null, $ydata)){
		foreach ($ydata as $k => $v) {
				if($v[$y_date]){
                 $data_city[$k] = $v[$y_date];
                 $data[$k] = $v[$count_type];
				} 
		     }
		}else{
			array_pop($ydata);
			foreach ($ydata as $k => $v) {
                 $data_city[$k] = $v[$y_date];
                 $data[$k] = $v[$count_type];
			 }
		}
       if($data_type){
	     	krsort($data_city);
	        krsort($data);
	    }
       return array(  
    	          'data_city' =>'"'.implode('","',$data_city).'"',
    	          'data' =>implode(',',$data),
    	          );
	}
	/**
	 *  author   : whh
	 *  function :查找二维数组的值是否存在，存在返回ture，不再存在返回false
	 *  date     : 2016-11-15
	 */
	function deep_in_array($value, $array) {   
	    foreach($array as $k=>$item) {   
	        if(!is_array($item)) {   
	            if ($item == $value) {  
	                return true;  
	            } else {  
	                continue;   
	            }  
	        }   
	            
	        if(in_array($value, $item)) {  
	            return true;      
	        } else if(deep_in_array($value, $item)) {  
	            return true;      
	        }  
	    }   
	    return false;   
	}
	/**
	 *  author   : whh
	 *  function : 获取近期时间每天通话各运营商通话数据
	 *  date     : 2016-10-25
	 */
	function reportCorpData($where){
	//function reportCorpData(){
         $cdr = M('cdr');
        $result = $cdr->field('FROM_UNIXTIME(call_time,"%Y-%m-%d") days, call_corp,count(cdr_id)')->where('1 '.$where)->group('days,call_corp')->order('days desc')->limit(390)->select();
        //$result = $cdr->field('FROM_UNIXTIME(call_time,"%Y%m%d") days,corp, count(cdr_id)')->where(1)->group('days,corp')->order('days desc')->limit(30)->select();
        // F('dcdc',$cdr->getlastsql());
        if(!$result){
             $result = array(0=>array(
				             	 'days' => 0,
				                 'call_corp' => 0,
				                 'count(cdr_id)' =>0, ),);
            }
               
         return  $result ;
	}
	/**
	 *  author   : whh
	 *  function : 运营商数据转换
	 *  date     : 2016-10-25
	 */
	function reportCorpGetData($ydata){
			foreach ($ydata as $k => $v) {
			    $data[$v['days']][$v['call_corp']] = $v['count(cdr_id)'];
			}
			//print_r($data);
			foreach ($data as $k1 =>$v1) {
				$cl = 0;
			    if($v1[102]){
			    	$data1[] = $v1[102];
			    	$cl = 1;
			    }else{
                    $data1[] = 0;
			    }
			     if($v1[103]) {
			    	$data2[] = $v1[103];
			    	$cl = 1;
			    }else{
                    $data2[] = 0;
			    }  
			    if($v1[105]) {
			    	$data3[] = $v1[105];
			    	$cl = 1;
			    }else{
                    $data3[] = 0;
			    }
			    if($v1[104]) {
			    	$data4[] = $v1[104];
			    	$cl = 1;
			    }else{
                    $data4[] = 0;
			    }
			    
			}
			$xdate = array_keys($data);
			foreach ($xdate as  $value) {

				$x_date[]="'".substr($value ,5)."'";
			}
			krsort($x_date);
			krsort($data1);
			krsort($data2);
			krsort($data3);
			krsort($data4);
	 		return array(
	              'x_date'  =>implode(',',$x_date),   
    	          'data_yd' =>implode(',',$data1),
    	          'data_lt' =>implode(',',$data2),
    	          'data_dx' =>implode(',',$data3),
    	          'data_qt' =>implode(',',$data4),
    	          );
	}

	/**
	 * 转换年月日  2018-10-02 2018年10月2号
	 * $time_type  时间类型：true时是时间戳 false时是date时间类型   $date  时间参数 
	 * $date_type:传入y,输出中文时间  年月日  传入h,输出中文时间  时分秒  空值输出 年月日时分秒   
	 * 2016-11-01
	 * whh
	 */
	function formart_date($time_type,$date,$date_type){
		if($time_type){
           $time_now = date('Y-m-d H:i:s',$date);
        }else{
           $time_now = $date;
        }
		$year=((int)substr($time_now,0,4));//取得年份

        $month=((int)substr($time_now,5,2));//取得月份

        $day=((int)substr($time_now,8,2));//取得几号

        $hour=((int)substr($time_now,11,2));//取得小时

        $minute=((int)substr($time_now,14,2));//取得分钟

        $second=((int)substr($time_now,17,2));//取得秒
        switch ($date_type) {
        	case 'y':
        		$now_date = $year.'年'.$month.'月'.$day.'日' ;
        		break;
        	case 'h':
        		$now_date = $hour.'时'.$minute.'分'.$second.'秒' ;
        		break;
        	
        	default:
        		$now_date = $year.'年'.$month.'月'.$day.'日'.$hour.'时'.$minute.'分'.$second.'秒' ;
        		break;
        }
        return $now_date;

	}

	   //发送邮件  whh  2017.03.24
	function  SendMail($address,$title,$message)
	{
		import('ORG.Util.PHPMailer');

		$mail= new PHPMailer();
		// 设置PHPMailer使用SMTP服务器发送Email
		$mail->IsSMTP();
		// 设置邮件的字符编码，若不指定，则为'UTF-8'
		$mail->CharSet='UTF-8';
		// 添加收件人地址，可以多次使用来添加多个收件人
		$mail->SMTPSecure = "ssl"; // 安全协议 
		$mail->Port = 465; // SMTP服务器的端口号 
		$mail->AddAddress($address);
		// 设置邮件正文
		//$mail->Body=$message;
		$mail->MsgHTML($message); 
		// 设置邮件头的From字段。
		$mail->From=C('MAIL_ADDRESS');
		// 设置发件人名字
		$mail->FromName=C('MAIL_NAME');
		// 设置邮件标题
		$mail->Subject=$title;
		// 设置SMTP服务器。
		$mail->Host=C('MAIL_SMTP');
		// 设置为“需要验证”
		$mail->SMTPAuth=true;
		// 设置用户名和密码。
		$mail->Username=C('MAIL_LOGINNAME');
		$mail->Password=C('MAIL_PASSWORD');
		// 发送邮件。
		return($mail->Send());
    }

     /**
 * 对象 转 数组
 *
 * @param object $obj 对象
 * @return array
 */
function object_to_array($obj) {
    $obj = (array)$obj;
    foreach ($obj as $k => $v) {
        if (gettype($v) == 'resource') {
            return;
        }
        if (gettype($v) == 'object' || gettype($v) == 'array') {
            $obj[$k] = (array)object_to_array($v);
        }
    }
 
    return $obj;
}
	

    //调用接口,立即发送短信
    function sMessage($id){
    	   set_time_limit(300);
           header('Content-Type: text/plain; charset=utf-8');
    	   //导入阿里云短信SDK
    	   import("ORG.aldx.api_demo.Sms");
    	   $client = new SmsDemo();  
    	   // 单条发送
    	   //$li = $client->sendSms(18295522973,12315);  
    	   //多条发送
    	   //$li1 = $client->sendBatchSms(); 
    	   //查询短信 
    	   //$li1 = $client->querySendDetails(18295522973,"20180314");  
    	   // out($li,$li1);
    		$sms = M('short_message');
    		$short_messages = $sms->field('short_message_id,dest,content')->where('short_message_id= %d',$id)->select();
    		//out($short_messages);
    		if($short_messages){
    			foreach ($short_messages as $k => $v) {
    				 $obj_info = $client->sendSms($v['dest'],$v['content']);  
    	             $res = object_to_array($obj_info); 
    	             
    	            /* $res = array(
    	               "Message" => "OK",
    	               "RequestId" => "C5D9F345-AFDE-4CC6-9543-DCDB8BF8EA2E",
    	               "BizId" =>  "812910021008511974^0",
    	               "Code" => "OK",
    	             );*/
    				if($res['Code'] == 'OK'){//发送成功
    					$data['code']         = $res['Code'];
    					$data['message']      = $res['Message'];
    					$data['bizid']        = $res['BizId'];
    					$data['status']       = 464; //发送成功
    					$sms->where('short_message_id = %d',$v['short_message_id'])->save($data);
    				}else{
    					$data['report_id']    = $result;
    					$data['status']       = 465; //发送失败
    					$sms->where('short_message_id = %d',$v['short_message_id'])->save($data);
    				}
    			}
    		}
    	
    }
    //号码屏蔽
    function hidetel($phone){
        $IsWhat = preg_match('/(0[0-9]{2,3}[\-]?[2-9][0-9]{6,7}[\-]?[0-9]?)/i',$phone); //固定电话
        if($IsWhat == 1){
            return preg_replace('/(0[0-9]{2,3}[\-]?[2-9])[0-9]{3,4}([0-9]{3}[\-]?[0-9]?)/i','$1****$2',$phone);
        }else{
            return  preg_replace('/(1[3456789]{1}[0-9])[0-9]{4}([0-9]{4})/i','$1****$2',$phone);
        }
    }		
   	//公共调用函数，获取url返回值
	function execPostRequest($url,$fields){
		if(empty($url)){ return false;}
		
		$fields_string="";
		$fields['publicKey']=C('publicKey');
		$fields['ts']=time();
		ksort($fields);
		foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
		//rtrim($fields_string,'&');
		$fields_string_sign = $fields_string.'secret='.C('appSecret');
		$sign = md5($fields_string_sign);
		/*$data_string = 'publicKey='.C('publicKey').'&ts='.time().'&sign='.$sign.'&'.$fields_string;
		$data_string = rtrim($data_string,'&');*/
		
		$fields['sign']=$sign;
		$headers = array("Content-type: application/json;charset='utf-8'","Accept: application/json","Cache-Control: no-cache","Pragma: no-cache");
		//out($fields,json_encode($fields,true));
		$ch = curl_init();
		curl_setopt($ch,CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch,CURLOPT_POST,1);
		curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode($fields));
		curl_setopt($ch, CURLOPT_HTTPHEADER,$headers); 
		$result = curl_exec($ch);
		curl_close($ch);
		return $result;
	}
	  //用于连接mongo
    function mongoConnect($name){
        $connection = new MongoClient('mongodb://'.C('MONGODB'));
        if (empty($name)) {
        	$smartcrm_email = 'smartcrm_data';
        }else{
        	$smartcrm_email = $name;
        }
        
        $db = $connection->$smartcrm_email;
        return $db;
    }
    //插入mongon内容
    function mongoInsert($arr,$db=null){
    	$mongodb = mongoConnect();
    	if ($db) {
    	  $collection = $mongodb->$db;
    	}else{
    	  $collection = $mongodb->smartcrm_active_data;
    	}
    	
        $arr['create_time']=time();
        $arr['create_date']=date('Y-m-d H:i:s');
        $res = $collection->insert($arr);
        return $res;
        
    }
    //读取mongo一条数据
    function mongoFind($where,$db=null){
    	$mongodb = mongoConnect();
    	if ($db) {
    	  $collection = $mongodb->$db;
    	}else{
    	  $collection = $mongodb->smartcrm_active_data;
    	}
        $cursor         = $collection->findOne($where);
        return $cursor;
    	
    }
    //更新mongo一条数据
    function mongoUpdate($where,$data,$db=null){
    	$mongodb = mongoConnect();
    	if ($db) {
    	  $collection = $mongodb->$db;
    	}else{
    	  $collection = $mongodb->smartcrm_active_data;
    	}
        $cursor         = $collection->update($where,$data);
        return $cursor;
    	
    }
    /**
     * [getNeedBetween 获取字符串特殊字符之间的字符]
     * @Author   Whh        wanghehui@kingwisoft.com
     * @DateTime 2018-11-14
     * @param    [param]
     * @param    [param]
     * @param    [type]     $kw1                     [字符串]
     * @param    [type]     $mark1                   [特殊字符1]
     * @param    [type]     $mark2                   [特殊字符2]
     * @return   [type]                              [description]
     */
    function getNeedBetween($kw1,$mark1,$mark2){
	    $kw=$kw1;
	    $kw='123'.$kw.'123';
	    $st =stripos($kw,$mark1);
	    $ed =stripos($kw,$mark2);
	    if(($st==false||$ed==false)||$st>=$ed)
	    return 0;
	    $kw=substr($kw,($st+1),($ed-$st-1));
	    return $kw;
    }


  //加密
      function encryptPhone($encryptStr) {
         $localIV = "0123456789abcdef";
         $encryptKey = "abcdef0123456789";
  
         //Open module
         $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, $localIV);
  
         //print "module = $module <br/>" ;
  
         mcrypt_generic_init($module, $encryptKey, $localIV);
  
         //Padding
         $block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
         $pad = $block - (strlen($encryptStr) % $block); //Compute how many characters need to pad
         $encryptStr .= str_repeat(chr($pad), $pad); // After pad, the str length must be equal to block or its integer multiples
  
         //encrypt
         $encrypted = mcrypt_generic($module, $encryptStr);
  
         //Close
         mcrypt_generic_deinit($module);
         mcrypt_module_close($module);
  
         return base64_encode($encrypted);
  
     }
  
     //解密
    function decryptPhone($encryptStr) {
         $localIV = "0123456789abcdef";
         $encryptKey = "abcdef0123456789";
  
         //Open module
         $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, $localIV);
  
         //print "module = $module <br/>" ;
  
         mcrypt_generic_init($module, $encryptKey, $localIV);

  
         $encryptedData = base64_decode($encryptStr);

         $encryptedData = mdecrypt_generic($module, $encryptedData);
          
         return rtrim($encryptedData,'');
     }

     function cut_str($str,$len,$suffix="..."){
        if(function_exists('mb_substr')){
            if(strlen($str) > $len){
                $str= mb_substr($str,0,$len).$suffix;
            }
            return $str;
        }else{
            if(strlen($str) > $len){
                $str= substr($str,0,$len).$suffix;
            }
            return $str;
        }         
    }

	

	
   
	
	
